Introduction

Users communicate with the kernel through a program known as the shell.

The shell is a command line interpreter; it translates commands entered by the user and converts them into a language that is understood by the kernel.

Shell is an environment in which we can run our commands, programs, and shell scripts. A shell provides an interface to your Linux System. It gathers your inputs and executes programs based on that input.

The shell is, after all, a real programming language, complete with variables, control structures, and so forth.

Shell Scripts

The basic concept of a shell script is a list of commands, which are listed in the order of execution. A good shell script will have comments, preceded by # sign, describing the steps.

  1. Create

    The .sh file is start by using #! /bin/sh , which alert the system that shell scripts are as follows.

1
2
3
#!/bin/bash
echo -e "Hello World! \a \n"
exit 0
  1. Comments

We can add some comments by using # in the begin of a line.

  1. Execute

    Make the script executable and execute it.

    1
    chmod +x test.sh ;./test.sh

Example

The following script uses the read command which takes the input from the keyboard and assigns it as the value of the variable PERSON and finally prints it on STDOUT.

1
2
3
4
#!/bin/sh
echo "What is your name?"
read PERSON
echo "Hello, $PERSON"

Here is a sample run of the script −

1
2
3
4
5
$./test.sh
What is your name?
Zara Ali
Hello, Zara Ali
$

The execution sequence of commands

  • ;

    The commands can be combined in a line by using the ; to sperate them.

    **It is noticeable that the commands will be executed from left to right and the fail of the previous commands don’t prevent the later ones. **

  • &&

    This operator just like the previous one but the obvious difference is that if the previous commands don’t be executed successfully, the later commands won’t be executed.

  • ||

    **ONLY the fail of the previous command can the later ones be executed. **

Variables

Variable is nothing more than a pointer to the actual value.

Defining Variables

Remember that there are not spaces between the ‘=’.

1
variable_name=variable_value
1
2
3
4
5
6
erro:
name = ferry
name= ferry chan
correct:
name=ferry
name="ferry chan"
  • The default type of variable is string type. If you want to perform arithmetic operations, you should declare the type of variables using the declare command.

    1
    2
    3
    4
    5
    6
    declare [-aAfFgilnrtux] [-p] [name[=value] ...]

    Options which set attributes:
    -a to make NAMEs indexed arrays (if supported)
    -i to make NAMEs have the `integer' attribute
    -x to make NAMEs export
    example
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    $ sum=10+10
    $ echo $sum
    10+10

    $ sum=$((10+10))
    $ echo $sum
    20

    $ declare -i sum=10+10
    $ echo sum

Accessing Values

To access the value stored in a variable, prefix its name with the dollar sign ($)

Unsetting Variables

Following is the syntax to unset a defined variable using the unset command −

1
unset variable_name

Special Variable

Sr.No. Variable & Description
1 $0The filename of the current script.
2 $nThese variables correspond to the arguments with which a script was invoked. Here n is a positive decimal number corresponding to the position of an argument (the first argument is $1, the second argument is $2, and so on).
3 **$#**The number of arguments supplied to a script.
4 **$**All the arguments are double quoted. If a script receives two arguments, $ is equivalent to $1 $2.
5 **$@**All the arguments are individually double quoted. If a script receives two arguments, $@ is equivalent to $1 $2.
6 **$?**The exit status of the last command executed.
7 **$$**The process number of the current shell. For shell scripts, this is the process ID under which they are executing.
8 **$!**The process number of the last background command.

Example

1
2
3
4
5
6
7
#!/bin/bash

echo "The script name is ==> ${0}"
echo "Total parameter number is ==>$#"
echo "Your whole parameter is ==>'$@'"
echo "The 1st parameter ==>${1}"
echo "The second parameter ==>${2}"
1
2
3
4
5
The script name is	==> ./how_paras.sh
Total parameter number is ==>3
Your whole parameter is ==>'a b c'
The 1st parameter ==>a
The second parameter ==>b

Exit Status

The $? variable represents the exit status of the previous command.

Exit status is a numerical value returned by every command upon its completion. As a rule, most commands return an exit status of 0 if they were successful, and 1 if they were unsuccessful.

Array

1
2
3
4
5
6
7
8
9
#!/bin/bash

NAME[0]="Zara"
NAME[1]="Qadir"
NAME[2]="Mahnaz"
NAME[3]="Ayan"
NAME[4]="Daisy"
echo "First Method: ${NAME[*]}"
echo "Second Method: ${NAME[@]}"

Operators

  • $((expression))

    We usually use it to calculate and return the result.

    factorial
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    #! /bin/bash

    read -p "Enter the value of n, I will calculate the factorial of n:" n
    s=$n
    while [ $n -gt 1 ]
    do
    n=$((n-1))
    s=$(($s*$n))
    done
    echo -e "The factorial is $s"
  • expr or awk

    Bourne shell didn’t originally have any mechanism to perform simple arithmetic operations but it uses external programs, either awk or expr.

    The following example shows how to add two numbers −

    1
    2
    3
    4
    #!/bin/sh

    val=`expr 2 + 2`
    echo "Total value : $val"

    It is noticeable that the $() and two ` can output the information of the executed command.

    The above script will generate the following result −

    1
    Total value : 4

    The following points need to be considered while adding −

    • There must be spaces between operators and expressions. For example, 2+2 is not correct; it should be written as 2 + 2.
    • The complete expression should be enclosed between ``, called the backtick.

Quoting

  1. double quoting

    The double quote ( “quote” ) protects everything enclosed between two double quote marks except $, ‘, “ and .

    (Use the double quotes when you want only variables and command substitution.)

  2. The single quote

    The single quote ( ‘quote’ ) protects everything enclosed between two single quote marks. It is used to turn off the special meaning of all characters.

[]

It is very important to understand that all the conditional expressions should be placed inside square braces with spaces around them. For example, [ $a -le $b ] is correct whereas, [$a -le $b] is incorrect.

In addition, there are two spaces around the operator.

Arithmetic Operators

Operator Description Example
+ (Addition) Adds values on either side of the operator expr $a + $b will give 30
- (Subtraction) Subtracts right hand operand from left hand operand expr $a - $b will give -10
* (Multiplication) Multiplies values on either side of the operator expr $a \* $b will give 200
/ (Division) Divides left hand operand by right hand operand expr $b / $a will give 2
% (Modulus) Divides left hand operand by right hand operand and returns remainder expr $b % $a will give 0
= (Assignment) Assigns right operand in left operand a = $b would assign value of b into a
== (Equality) Compares two numbers, if both are same then returns true. [ $a == $b ] would return false.
!= (Not Equality) Compares two numbers, if both are different then returns true. [ $a != $b ] would return true.

Relational Operators

Assume variable a holds 10 and variable b holds 20 then −

Operator Description Example
-eq(equal) Checks if the value of two operands are equal or not; if yes, then the condition becomes true. [ $a -eq $b ] is not true.
-ne(not equal) Checks if the value of two operands are equal or not; if values are not equal, then the condition becomes true. [ $a -ne $b ] is true.
-gt(greater than) Checks if the value of left operand is greater than the value of right operand; if yes, then the condition becomes true. [ $a -gt $b ] is not true.
-lt(less than) Checks if the value of left operand is less than the value of right operand; if yes, then the condition becomes true. [ $a -lt $b ] is true.
-ge(greater or equal) Checks if the value of left operand is greater than or equal to the value of right operand; if yes, then the condition becomes true. [ $a -ge $b ] is not true.
-le(less or equal) Checks if the value of left operand is less than or equal to the value of right operand; if yes, then the condition becomes true. [ $a -le $b ] is true.

Conditional Statements

Unix Shell supports conditional statements which are used to perform different actions based on different conditions.

Syntax

1
2
3
4
5
6
7
8
9
10
11
12
if [ expression 1 ]
then
Statement(s) to be executed if expression 1 is true
elif [ expression 2 ]
then
Statement(s) to be executed if expression 2 is true
elif [ expression 3 ]
then
Statement(s) to be executed if expression 3 is true
else
Statement(s) to be executed if no expression is true
fi

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#!/bin/bash

a=10
b=20

if [ $a == $b ]
then
echo "a is equal to b"
elif [ $a -gt $b ]
then
echo "a is greater than b"
elif [ $a -lt $b ]
then
echo "a is less than b"
else
echo "None of the condition met"
fi

Loops

Syntax

1
2
3
4
5
6
while [ condition ]
do
command1
command2
command3
done
1
2
3
4
5
6
for (( EXP1; EXP2; EXP3 ))
do
command1
command2
command3
done
1
2
3
4
5
6
for VARIABLE in 1 2 3 4 5 .. N
do
command1
command2
commandN
done

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#!/bin/sh

a=0
while [ "$a" -lt 10 ] # this is loop1
do
b="$a"
while [ "$b" -ge 0 ] # this is loop2
do
echo -n "$b "
b=`expr $b - 1`
done
echo
a=`expr $a + 1`
done
1
2
3
4
5
6
7
8
9
10
0
1 0
2 1 0
3 2 1 0
4 3 2 1 0
5 4 3 2 1 0
6 5 4 3 2 1 0
7 6 5 4 3 2 1 0
8 7 6 5 4 3 2 1 0
9 8 7 6 5 4 3 2 1 0

NOTE

  1. It is important to note how echo -n works here. Here -n option lets echo avoid printing a new line character.
  2. Among the [], we use a condition statement with two spaces between it. [ condition ]
1
2
3
4
5
6
7
8
9
#!/bin/bash
for((i=1;i<=9;i++))
do
for((j=1;j<=i;j++))
do
echo -n "$i*$j=$(($i*$j)) "
done
echo ""
done

output

1
2
3
4
5
6
7
8
9
1*1=1
2*1=2 2*2=4
3*1=3 3*2=6 3*3=9
4*1=4 4*2=8 4*3=12 4*4=16
5*1=5 5*2=10 5*3=15 5*4=20 5*5=25
6*1=6 6*2=12 6*3=18 6*4=24 6*5=30 6*6=36
7*1=7 7*2=14 7*3=21 7*4=28 7*5=35 7*6=42 7*7=49
8*1=8 8*2=16 8*3=24 8*4=32 8*5=40 8*6=48 8*7=56 8*8=64
9*1=9 9*2=18 9*3=27 9*4=36 9*5=45 9*6=54 9*7=63 9*8=72 9*9=81

Substitution

The -e option enables the interpretation of backslash escapes.

The printing value of the variable is substituted by its value.

1
2
3
4
#!/bin/sh

a=10
echo -e "Value of a is $a \n"

Command Substitution

Command substitution is the mechanism by which the shell performs a given set of commands and then substitutes their output in the place of the commands.

Syntax

The command substitution is performed when a command is given as −

1
`command`

Example

1
2
3
4
#!/bin/sh

DATE=`date`
echo "Date is $DATE"

Upon execution, you will receive the following result −

1
Date is Thu Jul  2 03:59:57 MST 2009

Function

1
2
3
4
5
6
7
8
9
#!/bin/sh

# Define your function here
Hello () {
echo "Hello World"
}

# Invoke your function
Hello

Upon execution, you will receive the following output −

1
Hello World

Pass Parameters to a Function

You can define a function that will accept parameters while calling the function. These parameters would be represented by $1, $2 and so on.

1
2
3
4
5
6
7
8
9
#!/bin/sh

# Define your function here
Hello () {
echo "Hello World $1 $2"
}

# Invoke your function
Hello Zara Ali

Upon execution, you will receive the following result −

1
Hello World Zara Ali

Returning Values from Functions

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#!/bin/sh

# Define your function here
Hello () {
echo "Hello World $1 $2"
return 10
}

# Invoke your function
Hello Zara Ali

# Capture value returnd by last command
ret=$?

echo "Return value is $ret"

Upon execution, you will receive the following result −

1
2
Hello World Zara Ali
Return value is 10