Bash Scripting
Bash Scripting
WHAT IS SHELL ?
A Shell provides you with an interface to the Unix system. It gathers input from you and
executes programs based on that input. When a program finishes executing, it displays that
program's output.
TYPES OF SHELLS:
There are two major types of shells in unix .These are
BOURNE SHELL
This is a default shell for version 7 unix. The Character $ is the default prompt for the bourne
shell .The different subcategories in the shell are korn shell,Bourne again shell,POSIX shell etc.
C SHELL
This is a unix shell and a command processor that is run in a text window.The character % is the
default prompt for the c shell.File commands can also read easily by the C shell which is known
as a script.
Batch Jobs
Programming
Generalisation
Shortcuts
The sign #! is called she-bang and is written at top of the script. It passes instruction to
program /bin/sh. To run your script in a certain shell (shell should be supported by your
system), start your script with #! followed by the shell name.
we create a test.sh script. Note all the scripts would have the .sh extension. Before you add
anything else to your script, you need to alert the system that a shell script is being started. This
is done using the shebang construct. For example
#!/bin/sh
This tells the system that the commands that follow are to be executed by the bourne shell
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
read PERSON
Chmod +X 1.sh
./1.sh or sh 1.sh
VARIABLES:
A variable is a character string to which we assign a value. The value assigned could be a
number, text, filename, device, or any other type of data
VARIABLE NAMES :
The name of a variable can contain only letters (a to z or A to Z), numbers ( 0 to 9) or the
underscore character ( _). By convention, Unix shell variables will have their names in
UPPERCASE
TYPES OF VARIABLES:
System variables
They are created & defined by unix or linux os .They are predefined variables defined by
os
EX: $BASH,$BASH_VERSION,$HOME,$PWD etc
User defined variables
They are created and maintained by us
DEFINING VARIABLES:
Variable_name =variable_value
The above example defines the variable NAME and assigns the value “chandana” to it
ACCESSING VALUES:
To access the value stored ina variable ,prefix its name with the dollar sign ($).
For example, the following script will access the value of defined variable NAME and print it on
STDOUT
2. #!/bin/sh
NAME="chandana"
echo $NAME
READ_ONLY VARIABLES:
Shell provides a way to mark variables as read-only by using the read-only command. After a
variable is marked read-only, its value cannot be changed.
For example, the following script generates an error while trying to change the value of NAME
3. #!/bin/sh
NAME="chandana"
readonly NAME
NAME="chandu"
UNSETTING VARIABLES :
Unsetting or deleting a variable directs the shell to remove the variable from the list of variables
that it tracks. Once you unset a variable, you cannot access the stored value in the variable
4. #!/bin/sh
NAME="chandana"
unset NAME
echo $NAME
SPECIAL VARIABLES:
The following table shows a number of special variables that you can use in your shell scripts
5. #!/bin/sh
echo "file anme: $0"
SHELL ARRAYS:
A shell variable is capable enough to hold a single value.These variables are called scalar
variables.Shell supports a different type of variable called an array variable.This an hold
multiple values at the same time.Arrays provide a method of grouping a set of variables
The difference between an array variable and a scalar variable can be explained as follows.Each
of the individual variables is a scalar variable as follows
NAME01=”chandana”
NAME02=”chandu”
Instead of this we can use a single array to store all the above mentioned names
array_name[index]=value
index -> it is the index of the item in the array that you want to set
If you are using the bash shell, here is the syntax of array initialization
Array_name=(value1..valuen)
Accessing Array Values:
After you have set any array variable, you access it as follows
${array_name[index]}
6. #!/bin/sh
NAME[0]="Zara"
NAME[1]="Qadir"
NAME[2]="Mahnaz"
NAME[3]="Ayan"
NAME[4]="Daisy"
You can access all the items In an array in one of the following ways
${array_name[*]}
${array_name[@]}
7. #!/bin/sh
NAME[0]="Zara"
NAME[1]="Qadir"
NAME[2]="Mahnaz"
NAME[3]="Ayan"
NAME[4]="Daisy"
echo "First Method: ${NAME[*]}"
echo "Second Method: ${NAME[@]}"
BASIC OPERATORS:
Bourne shell didn't originally have any mechanism to perform simple arithmetic operations but
it uses external programs, either awk or expr
8. #!/bin/sh
Val = ‘expr 2 + 2’
Arithematic operators
[ $a == $b ] -> All the conditional expressions should be inside square braces with spaces
around them
RELATIONAL OPERATORS:
Bourne Shell supports the following relational operators that are specific to numeric values.
These operators do not work for string values unless their value is numeric
Ex: [ $a <= $b ] -> all the conditional exxpressions should be placed inside square braces
We have a few operators that can be used to test various properties associated with a unix file
-k file Checks if file has its sticky bit set; if [ -k $file ] is false.
yes, then the condition becomes
true.
9. #!/bin/sh
a=10
b=20
if [ $a -eq $b ]
then
else
fi
if [ $a -ne $b ]
then
else
fi
if [ $a -gt $b ]
then
else
fi
if [ $a -lt $b ]
then
else
fi
if [ $a -ge $b ]
then
else
fi
if [ $a -le $b ]
then
else
fi
STRING OPERATORS:
10. #!/bin/sh
a="abc" b="efg"
if [ $a = $b ]
then
fi
if [ $a != $b ]
then
fi
if [ -z $a ]
then
fi
if [ -n $a ]
then
fi
if [ $a ]
then
fi
FOR LOOP:
The for loop operates on lists of items. It repeats a set of commands for every item in a list.
11. #!/bin/sh
for i in {1..10}
do
done
12. #!/bin/sh
do
done
IF:
The if..fi statement is the fundamental control statement that allows shell to make decisions and
execute statements conditionally
SYNTAX:
if[expression]
then
fi
13. #!/bin/sh
if [ $1 –gt 100]
then
pwd
fi
IF ELSE:
The if..else..fi statement is the next form of control statement that allows shell to execute statements in
a controlled way and make the right choice
14. #!/bin/bash
#a=20
#b=40
if [ $a == $b ]
then
else
fi
IF ELIF:
The if...elif...fi statement is the one level advance form of control statement that allows Shell to make
correct decision out of several conditions.
15. #!/bin/sh
a=30
b=40
c=20
if [ $a -gt $b ]
then
elif [ $a -gt $c ]
then
else
fi
WHILE LOOP:
The while loop enables you to execute a set of commands repeatedly until some condition occurs. It is
usually used when you need to manipulate the value of a variable repeatedly
16. #!/bin/bash
c=1
while [ $c -le 10 ]
do
(( c++ ))
Done
17. #!/bin/sh
a=0
do
b="$a"
do
b=`expr $b - 1`
done
echo
a=`expr $a + 1`
done
Note: Here -n option lets echo avoid printing a new line character.
WHAT IS SUBSTITUTION?
The shell performs substitution when it encounters an expression that contains one or more special
characters
Ex: Here the printing value of the variable is substituted by its value .same time .”\n” is substituted by a
new line
18.#!/bin/sh #!/bin/sh
A=10 a=10
The following are the escape sequences which can be used in echo command
1. \\ backslash
2. \a alert(BEL)
3. \b backspace
4. \c suppress trailing newline
5. \f form feed
6. \n new line
7. \r carriage return
8. \t horizontal tab
9. \v vertical tab
You can use the -E option to disable the interpretation of the backslash escapes (default).
You can use the -n option to disable the insertion of a new line.
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:
`command`
When performing the command substitution make sure that you use the backquote, not the single quote
character.
!/bin/sh
DATE=`date`
echo "Date is $DATE"
VARIABLE SUBSTITUTION:
Variable substitution enables the shell programmer to manipulate the value of a variable based on its state.
19.#!/bin/sh
unset var
var="Prefix"
SHELL FUNCTIONS:
Functions enable you to break down the overall functionality of a script into smaller, logical
subsections, which can then be called upon to perform their individual tasks when needed.
Using functions to perform repetitive tasks is an excellent way to create code reuse. This is an
important part of modern object-oriented programming principles.
Creating functions
Function_name () {
List of commands
The name of your function is function_name and that’s what you will use to call it from
elsewhere in your scripts.The function name must be followed by parentheses followed by a
list of commands enclosed within braces
20.#!/bin/sh
# Define your function here
Hello () {
If you execute an exit command from inside a function, its effect is not only to terminate execution of
the function but also of the shell program that called the function.
If you instead want to just terminate execution of the function, then there is way to come out of a
defined function.
21.#!/bin/sh
Hello () {
return 10
ret=$?
NESTED FUNCTIONS:
One of the more interesting features of functions is that they can call themselves and also other
functions. A function that calls itself is known as a recursive function.
22.#!/bin/sh
number_one () {
number_two
number_two () {
number_one
read color
case $color in
Red)
;;
Green)
;;
Blue)
echo "Sky is blue"
;;
*)
;;
esac
FAQS:
10. Print content of input file if exist else create a new file with content "Hello World"
#!/bin/sh
echo "enter a filename:"
read name
if [ -f $name ]
then
echo " file is found "
cat $name
else
echo hello world >hello.txt
fi
13. Write a Scheduling code to read log files, compress and zip,
write to Log Server host.
#!/bin/bash
log_dir="/var/log"
log_server="example.com"
log_username="username"
log_password="password"
for log_file in $(ls $log_dir/*.log)
do
gzip $log_file
scp "${log_file}.gz" ${log_username}@${log_server}:/logs/
done;wq