1. Some bash shell scripting rules
1) The first line in your script must be
#!/bin/bash
That is a # (Hash) followed by a ! (ban) followed by the path of the shell. This line lets the environment know the file is a shell script and the location of the shell.
2) Before executing your script, you should make the script executable.
$ chmod ugo+x test.sh
3) The name of your shell script must end with a .sh .
Example 1.1: First shell script
a.
$ vi my_shell_script.sh
b.
#!/bin/bash
echo “Hello World “
c.
$ chmod +x my_shell_script.sh
d.
$ ./ my_shell_script.sh
2. Conditional statements
The ‘if’ Statement - evaluates a condition which accompanies its command line.
Syntax 2.1:
if condition_is_true
then
execute commands
fi
Syntax 2.2:
if condition_is_true
then
execute commands
else
execute commands
fi
if condition also permits multiway branching. That is you can evaluate more conditions if the previous condition fails.
Syntax 2.3:
if condition_is_true
then
execute commands
elif another_condition_is_true
then
execute commands
else
execute commands
fi
3. if’s companion - test
test is an internal feature of the shell. test evaluates the condition placed on its right, and returns either a true or false exit status. For this purpose, test uses certain operators to evaluate the condition. They are as follows:
3.1 Relational operators
-eq Equal to
-lt Less than
-gt Greater than
-ge Greater than or equal to
-lt Less than
-le Less than or equal to
3.2 File related tests
-f file True if file exists and is a regular file
-r file True if file exists and is readable
-w file True if file exists and is writable
-x file True if file exists and is executable
-d file True if file exists and is a directory
-s file True if file exists and has a size greater than zero.
3.3 String tests
-n str True if string str is not a null string
-z str True if string str is a null string
str1 == str2 True if both strings are equal
str1 != str2 True if both strings are unequal
str True if string str is assigned a value and is not null.
3.4 Multiple conditions
-a Performs the AND function
-o Performs the OR function
Example 3.1:
if [ $D -eq 25 ]
then
echo $D
fi
Example 3.2:
if [ $STR1 == $STR2 ]
then
do something
fi
Example 3.3:
if [ -n "$STR1" -a -n "$STR2" ]
then
echo ‘Both $STR1 and $STR2 are not null’
fi
… above, I have checked if both strings are not null then execute the echo command.
Things to remember while using test
If you are using square brackets [] instead of test, then care should be taken to insert a space after the [ and before the ].
Note: test is confined to integer values only. Decimal values are simply truncated.
4. Case statement
Case statement is the second conditional offered by the shell.
Syntax:
case expression in
pattern1) execute commands ;;
pattern2) execute commands ;;
…
esac
The keywords here are in, case and esac. The ‘;;’ is used as option terminators. The construct also uses ‘)’ to delimit the pattern from the action.
Example 4.1:
…
echo “Enter your option : “
read I;
case $I in
1) ls -l ;;
2) ps -aux ;;
3) date ;;
4) who ;;
5) exit
esac
Note: The last case option need not have ;;
but you can provide them if you want.
Example 4.2:
case `date +%a` in
Mon) commands ;;
Tue) commands ;;
Wed) commands ;;
…
esac
5. Looping Statements
5.1 while loop
Syntax:
while condition_is_true
do
execute commands
done
Example 5.1.1:
while [ $NUM -gt 100 ]
do
sleep 5
done
Example 5.1.2:
while :
do
execute some commands
done
The above code implements a infinite loop. You could also write ‘while true’ instead of ‘while :’ .
5.2 until loop
Until complements while construct in the sense that the loop body here is executed repeatedly as long as the condition remains false.
Syntax:
until false
do
execute commands
done
Example 5.2:
…
until [ -f myfile ]
do
sleep 5
done
The above code is executed repeatedly until the file myfile is created(touch).
5.3 for loop
Syntax :
for variable in list
do
execute commands
done
Example 5.3.1:
…
for X in 1 2 3 4 5
do
echo “The value of X is $X”;
done
Example 5.3.2:
#!/bin/bash
LIMIT=10
for ((a=1; a <= LIMIT ; a++))
do
echo -e “$a”
done
6. special symbols and their meanings w.r.t shell scripts
$* - This denotes all the parameters passed to the script at the time of its execution. Which
includes $1, $2 and so on.
$0 - Name of the shell script being executed.
$# - Number of arguments specified in the command line.
$? - Exit status of the last command.
$$ - contains the process ID of the current shell.
The above symbols are known as positional parameters. Let me explain the positional parameters with the aid of an example. Suppose I have a shell script called my_script.sh . Now I execute this script in the command line as follows :
$ ./my_script.sh linux is a robust OS
… as you can see above, I have passed 5 parameters to the script. In this scenario, the values of the positional parameters are as follows:
$* - will contain the values ‘linux’,’is’,’a’,’robust’,’OS’.
$0 - will contain the value my_script.sh - the name of the script being
executed.
$# - contains the value 5 - the total number of parameters.
$$ - contains the process ID of the current shell. You can use this parameter while giving unique names to any temporary files that you create at the time of execution of the shell.
$1 - contains the value ‘linux’
$2
- contains the value ‘is’
… and so on.
7. Read statement
Make your shell script interactive. read will let the user enter values while the script is being executed. When a program encounters the read statement, the program pauses at that point. Input entered through the keyboard id read into the variables following read, and the program execution continues.
Example 7.1: Interactive
#!/bin/bash
echo “Enter your name : “
read NAME
echo “Hello $NAME , Have a nice day.”
Exit status of the last command
Every command returns a value after execution. This value is called the exit status or return value of the command. A command is said to be true if it executes successfully, and false if it fails. This can be checked in the script using the $? positional parameter.
Example x: Multiplication Table
#!/bin/bash
Y=1
while [ $Y -le 12 ]; do
X=1
while [ $X -le 12 ]; do
printf “% 4d” $(( $X * $Y ))
let X++
done
echo “”
let Y++
done
8. Function
We can break our code into small chunks called functions, and call them by name in the main program. This approach helps in debugging, code re-usability, etc.
Syntax:
<name of function> ()
{ # start of function
statements
} # end of function
Functions are invoked by citing their names in the main program, optionally followed by arguments.
Example 8.1:
#!/bin/bash
#******************************************************
# This script uses function
#******************************************************
sumcalc ()
{
SUM=$[$1 + $2]
}
echo -e “Enter the first number:\c”
read NUM1
echo -e “Enter the second number:\c”
read NUM2
sumcalc $NUM1 $NUM2
echo “Output from function sumcalc: $SUM”