Shell & Shell scripts
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.
Create
The
.shfile is start by using#! /bin/sh, which alert the system that shell scripts are as follows.
1 | !/bin/bash |
- Comments
We can add some comments by using # in the begin of a line.
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 | #!/bin/sh |
Here is a sample run of the script −
1 | $./test.sh |
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 | erro: |
The default type of variable is string type. If you want to perform arithmetic operations, you should declare the type of variables using the
declarecommand.1
2
3
4
5
6declare [-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 exportexample 1
2
3
4
5
6
7
8
9
10sum=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 | !/bin/bash |
1 | The script name is ==> ./how_paras.sh |
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 | !/bin/bash |
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"exprorawkBourne 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
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.)
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 | if [ expression 1 ] |
Example
1 | !/bin/bash |
Loops
Syntax
1 | while [ condition ] |
1 | for (( EXP1; EXP2; EXP3 )) |
1 | for VARIABLE in 1 2 3 4 5 .. N |
Example
1 | !/bin/sh |
1 | 0 |
NOTE
- It is important to note how echo -n works here. Here -n option lets echo avoid printing a new line character.
- Among the
[], we use a condition statement with two spaces between it.[ condition ]
1 | !/bin/bash |
output
1 | 1*1=1 |
Substitution
The -e option enables the interpretation of backslash escapes.
The printing value of the variable is substituted by its value.
1 | !/bin/sh |
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 | !/bin/sh |
Upon execution, you will receive the following result −
1 | Date is Thu Jul 2 03:59:57 MST 2009 |
Function
1 | !/bin/sh |
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 | !/bin/sh |
Upon execution, you will receive the following result −
1 | Hello World Zara Ali |
Returning Values from Functions
1 | !/bin/sh |
Upon execution, you will receive the following result −
1 | Hello World Zara Ali |
