Test your knowledge!Take a quiz to access yourself.

Command Line Arguments and Exit Status in Shell Scripting

Shell scripting and Linux commands, these are powerful and you might not realize that, but when you keep on using them, you will understand. For instance the command in above image sudo rm -rf /, seems simple and you should think thousand time before running it on your machine (till now if you haven’t run it 😛 ). As this will delete all the files and folders recursively from / (root of machine) with root permission. Till the time you would realize it a disaster would have taken place.
So how can we be smart while writing commands, just learn all the commands with explanation and use them with your best state of mind. Learning Shell scripting is another way of doing it. We explained you how to start scripting and The Basics of Shell Scripting. To add to that knowledge we will learn today about few more interesting points about Shell Scripting.

Command line Arguments with Shell Script:

Shell Scripting provides us very interesting way of executing it, and that is by using Command line Arguments while calling the script name. Now you might be thinking how’s that interesting? That’s because Shell Script’s execution environment takes care of the arguments provided by us while running script and gives us few variables which helps in using arguments dynamically while writing logic.

Let’s say you provided few arguments while running shell script, those will be available in the shell script as positional parameters ($1, $2, $3, $4… etc). Important points to note are:

  1. $1 variables stores the first argument provided, and similarly rest all arguments are saved in their respective variable.
  2. $0 means the file name.
  3. Till 9th position we can access parameters like $9, but after that you have to use ${10}, ${11} and so on.

Here are few Shell Parameters Variables and their description:
$0                –     The filename of the current script.
$1, $2..       –    Positional Parameters representing command line arguments.
$#                –     Total number of arguments in the shell script.
$*                 –     Complete set of Positional Parameters as a single string.
[email protected]               –     Same as $*
$?                 –     The exit status of the last command executed.
$$                –     PID of the current shell.
$!                 –     PID of the last background command.

Let’s try to understand the concept of positional parameters with the help of an example:

#!/bin/bash
echo "File Name: $0"
echo "First Parameter : $1"
echo "Second Parameter : $2"
echo "Parameter Values: $*"
echo "Total Number of Parameters : $#"

And now let's execute the above script.
$./test.sh Ram Shyam
File Name : ./test.sh
First Parameter : Ram
Second Parameter : Shyam
Parameter Values: Ram Shyam
Total Number of Parameters : 2

Above example makes things easier to understand 🙂 .

Exit Status of a Command:

We just learned above that we can get exit status of just executed command by using $?. So what does that signify? How can we benefit from exit status of last executed command?

Exit status are significant, they tells us whether the last executed command was successful or not.

A return value of 0 ( zero ) means command has executed successfully without any errors and a value other than 0 signifies the failure in command execution. This has proven to be a very important concept in shell scripting.

$cat abc.sh
Cat: can’t open abc.sh
$echo $?
1            // a non-zero value indicates failure of the previous command

So we just came to know that above command failed, we can now execute some code which is as per this failed command case logic. Thus the importance of Exit Status.

Logical Operators &&(and) and ||(or) :

So after getting command line arguments and exit status we have to write some conditions which will help us in defining the flow of execution of script as per the input or other in-between responses from code.

Consider the script below:

#!/bin/sh
Filename=employee.txt
echo "Enter the employee name to be searched in the file"
read empname
grep "$empname" $Filename
echo "Task completed. Above are the employee details"

Above script search the employee’s details in employee.txt file.The user enters employee name, and using the read statement  its saved into empname variable. Grep command will return all the lines containing the employee name that the user will enter.

At the end of the script the echo command will execute irrespective of the success or failure of the grep command. Even if the grep command fails the script at the end will say “Task completed. Above are the employee details” which sounds a bit confusing. Hence to avoid such scenarios we can take help of operators

Command1 && Command2        //Command2 is executed only when Command1 is successful.
Command1 || Command2        //Command2 is executed only when Command1 fails.

It can easily solve above problem of returning a correct statement at the end of the script. It can be used as :

$ grep –i Ram employee.txt && echo "Task completed. Employee found."

Another way of making scripts to behave in a right manner is to use the conditional statements. Everyone will be familiar with the famous if.. else statements that are used in many programming languages. We will discuss them in next post. So just stay tune and post your questions in comment below. 🙂

3 Comments
    • gplus-profile-picture

Add a Comment

Your email address will not be published. Required fields are marked *