3. Introduction: Shell Program
On Unix systems, shell program acts as an interface between user
and operating system.
The shell program is executed for a user when a user logs in by
scanning /etc/passwd file (last entry has the shell program
name).
The most common used shell program is /bin/sh. On different
flavours of unix, /bin/sh may be a symbolic link or hard link to
actual scripting program.
www.opengurukul.com 3
4. Introduction: Shell Program
The current shell program that is in use is stored in environment
variable SHELL.
To find the current shell program, use following command
$ echo $SHELL
/bin/bash
$
www.opengurukul.com 4
5. Introduction: Popular Shell Programs
Shells which are more popular are -
i) bourne again shell (bash),
ii) korn shell (ksh)
iii) c shell (csh).
Linux uses bash (Bourne again shell) by default.
AIX uses korn shell by default.
There are other shells like posix shell, ksh93 etc.
The shell programs that are supported on the systems are
stored in the file /etc/shells on Linux.
www.opengurukul.com 5
6. Shell Scripting: Introduction : Shell
Supported
To find shells which are supported on your Linux system.
$ cat /etc/shells
/bin/sh
/bin/bash
/sbin/nologin
/bin/zsh
$
www.opengurukul.com 6
7. Shell Scripting: Introduction : Shell Script
Extension
The shell scripts generally ends with an extension .sh
(for korn and bourne shell).
It is not mandatory to have an extension.
www.opengurukul.com 7
8. Shell Scripting: Introduction : Shell Script
A sequence of command that we generally type on the
command prompt can be placed in a file and all the commands
can be executed at one shot.
The file which contains commands to be interpreted by shell
program is called shell script.
The first line in the shell script is generally.
#!/bin/sh
It indicates that /bin/sh should be used to interpret the lines in
the file.
www.opengurukul.com 8
9. Shell Scripting: Introduction : Create Shell
Script
Write a sequence of commands you would like to execute
in a file.
Ensure that the first line indicates the location of interpreter.
Example :
#!/bin/sh
# Example : hello_world.sh
echo Hello World
www.opengurukul.com 9
10. Shell Scripting: Introduction : Execute
Permissions on the Shell Script
The shell script can be made executable by using
$ chmod +x script_name.sh
www.opengurukul.com 10
12. Shell Scripting: Introduction: Exit Status
The exit command terminates a script.
The exit command can return a value, which is available to
the script's parent process.
Exit status of last command is stored in $?
When script ends with exit that has no parameter, exit
status of the script is the exit status of the last command
executed in the script.
Equivalent of a bare exit is exit $? or even just omitting the
exit.
www.opengurukul.com 12
13. Shell Scripting: Introduction: Exit Status
Significance of Value of Exit Status
0 indicates successful execution.
non-0 indicates failed execution.
Example : Success & Failure
Failure: Success:
$ ls /file/does/not/exist $ ls > /dev/null
$ echo $? $ echo $?
1 0
$ $
www.opengurukul.com 13
14. Shell Scripting: Introduction: Comments
Single Line
The character "#" (hash) is used to add # Example : comments.sh
single line comment in a shell script.
Anything that follows # is a comment. # This is a comment.
www.opengurukul.com 14
15. Shell Scripting: Introduction: Comments
Multple Line
The multi-line comment is # Example : comment_multi.sh
created in shell script using ':'
: ' i am
followed by a comment in
single quotes. a multi
line
Donot forget to put a space Comment '
between : (colon) and ' (single
quote).
www.opengurukul.com 15
17. Shell Scripting: Variables: List
To see the list of variables such as PATH, HOME etc, you can use
'env' command.
$ env
...
PATH=/bin:/sbin:/home/sachin/bin
HOME=/home/sachin
SHELL=/bin/bash
...
$
www.opengurukul.com 17
18. Shell Scripting: Variables : Export
New variables can be instantiated using
variable_name = variable_value
Variables are referenced using either $variable_name or $
{variable_name}.
www.opengurukul.com 18
19. Shell Scripting: Variables : Export: example
Example : Example :
$ export A=a
$ MYNAME=matsya $ echo $A123 # no output
$ export MYNAME $echo ${A}123
(or) A123
$ export MYNAME=matsya $
$ echo $MYNAME
www.opengurukul.com 19
20. Shell Scripting : Variables : Single
Quote vs Double Quote
In single quote, variable values are not expanded.
In double quote, variables values will expand.
We can use (escape sequence) before $ to remove
special meaning.
www.opengurukul.com 20
21. Shell Scripting : Variables : Single
Quote vs Double Quote : Example
#!/bin/sh
# Example : quote.sh
export USER=matsya1
echo without quotes : $USER # prints matsya1
echo "double quotes : $USER" # prints matsya1
echo 'single quote: $USER' # prints $USER
www.opengurukul.com 21
echo "escape sequence: $USER" # prints $USER
22. Shell Scripting: Variables : Data Types
Shell Variables are untyped.
We can use the same variable to store integer and string.
Example :
x=123;
x="hello"
www.opengurukul.com 22
23. Shell Scripting: Variables: Integer Variables
declare -i variable_name statement can be used to create integer
variables.
Program: Output:
$ cat integer_variables.sh $ sh integer_variables.sh
#!/bin/sh count : 10
declare -i count count : 0
count=10 $
echo "count : $count"
count="hello"
echo "count : $count"
$ www.opengurukul.com 23
24. Shell Scripting: Variables : Read-Only
Variables
declare -r var1 works the same as Program:
readonly var1, used to create $ cat -n readonly_variable.sh
read-only variable. #!/bin/sh
declare -r count=10
echo $count
count=20
echo $count
$
Output:
$ sh readonly_variable.sh
10
readonly_variable.sh: line 5: count:
www.opengurukul.com 24
readonly variable
25. Shell Scripting: Variables : The read
command
read variable_name will store the Program :
value read from keyboard into
variable_name
# Example : read_cmd.sh
echo "Enter your name "
read name
echo "Your name is $name"
Output :
$ sh read_cmd.sh
Enter your name Matsya Technologies
www.opengurukul.com 25
Your name is Matsya Technologies
26. Shell Scripting: Variables : REPLY Variable
The read command without a Program :
variable name will store the value # read_cmd_reply.sh
entered from keyboard into a built-
in variable REPLY.
echo "Enter your name"
read
echo "Your name is $REPLY"
Output :
$ sh read_cmd_reply.sh
Enter your name Matsya Tech
www.opengurukul.com 26
28. Shell Scripting: Program Arguments
Script Name
$0 is special argument and it contains name of the script itself.
Arguments
$1 is the first argument
$2 is the second argument and so on.
NOTE
To reference to 10th argument, we must use curly braces
around it.
E.g. ${10}. www.opengurukul.com 28
29. Shell Scripting: Program Arguments: Special
Built-in Variables
$# represents the parameter count.
Useful for controlling loop constructs that need to
process each parameter.
$@ expands to all the parameters separated by spaces.
Useful for passing all the parameters to some other
function or program.
$$ expands to the process id of the shell that invoked the
script.
Useful for creating unique temporary filenames relative
to this instantiation of the script.
www.opengurukul.com 29
31. Shell Scripting: Program
Arguments: $@ and $*
$@ behaves like $* except that Program :
when quoted the arguments are
# example : d_at.sh
broken up properly if there are
spaces in them. for var in ”$@”
do
echo "$var"
done :
Output
$ sh d_at.sh 1 2 '3 4'
1
2
34
www.opengurukul.com 31
$
32. Shell Scripting: Program
Arguments: $@ and $* : Example $*
Program : Program :
# example : d_star_quote.sh # example : d_star_noquotes.sh
for var in ”$*” for var in $*
do do
echo "$var" echo "$var"
done :
Output done :
Output
$ sh d_star_quote.sh 1 2 '3 4' $ sh d_star_noquotes.sh 1 2 '3 4'
1234 1
$ 2
www.opengurukul.com 32
3
33. Shell Scripting : Program Arguments:
$@ and $* : Example
# $@ in double quotes : correct way # $* in double quotes
dat_dq() { dstar_dq() {
echo '$@ in double quotes : ' echo '$* in double quotes : '
for var in "$@" ; do
for var in "$*" ; do
echo $var
echo $var
done
done
}
}
# $@ in no quotes
www.opengurukul.com 33
dat_nq() {
34. $ sh dstar_dat.sh
# $@ in no quotes $@ in double quotes :
dstar_nq() { 1
echo '$* without any quotes : ' 23
for var in $* ; do 4
echo $var $@ without any quotes :
done 1
} 2
3
dat_dq 1 '2 3' 4 4
dat_nq 1 '2 3' 4 $* without
www.opengurukul.com any quotes : 34
35. Shell Scripting: Program Arguments : shift
command
Shift
The shift command can be used to shift arguments to left side.
We can specify a count and we lose that many arguments on the left
side. For a shift of 1, $2 becomes $1 and so on.
For a shift of 2, $3 will become $1.
It is useful to process arguments in a loop using a single variable to
reference to argument one by one.
www.opengurukul.com 35
38. Shell Scripting: Misc : Command
Substitution
In a shell script, the output of a command can be substituted in place
of command name using following syntax.
$(command)
`command`
Such command will be executed in a sub-shell.
The standard output from sub shell will be used in the place of
command when the command completes.
www.opengurukul.com 38
39. Shell Scripting: Misc : Command
Substitution : Example
Program : Output :
# example : cmd_subst.sh
$ sh cmd_subst.sh 10 20
a=$1 sum : 30
b=$2 sum : 30
$
total=$(expr $a + $b)
echo "sum : $total"
total=`expr $a + $b`
echo "sum : $total" www.opengurukul.com 39
40. Shell Scripting: Misc : Arithmetic Expansion
Arithmetic expansion is also allowed and comes in the form:
$((expression))
The value of the expression will replace the substitution.
Example : will echo "8" to stdout.
#!/bin/sh
echo $((1+3+4))
www.opengurukul.com 40
41. Shell Scripting: Misc : Arithmetic
Expansion : Example
Program : Output :
# example : arith_expr.sh
$ sh ./arith_expr.sh 40 50
x=$1 90
y=$2 90
90
echo $(expr $x + $y) $
echo $(($x + $y))
www.opengurukul.com 41
43. Shell Scripting: Test Command
The test command or [ expression ] is used to check if an expression is true. If it is
true, 0(zero) is returned otherwise non-zero is returned.
$ test 1 -eq 1 # test equal to
$ echo $?
0
$
$ test 1 -eq 10 # test not equal to
$ echo $?
1
$
www.opengurukul.com 43
44. Shell Scripting: Test Command : Example
Program : Output :
# example : test_cmd.sh $ sh test_cmd.sh
if test 1 -eq 1 ; then test succeeded
echo "test succeeded"; $
fi
www.opengurukul.com 44
45. Shell Scripting: Test Command: Numbers
Use test command to compare numbers
Numeric Test Operators
-eq = equal to
-ne = not equal to
-lt = less than
-le = less than or equal to
-gt = greater than
www.opengurukul.com 45
46. Shell Scripting: Test Command: Numbers
Program : Output :
a1=$1
op=$2 $ sh test_cmd_num.sh 50 -eq 60
a2=$3
if test ${a1} $op ${a2}; then false
echo "true"
else false
echo "false"
fi $ sh test_cmd_num.sh 50 -eq 50
if [ ${a1} $op ${a2} ]; then
echo "true"
true
else
echo "false"
true
fi www.opengurukul.com 46
47. Shell Scripting: Test Command: Strings
String Tests
Equality s1 = s2
Inequality s1 != s2
Zero (Length is zero) -z str
Non-zero (Length is non-zero) -n str
www.opengurukul.com 47
48. Shell Scripting: Test Command: Strings
Program : Output :
# example : test_cmd_str.sh
$ sh test_cmd_str.sh in = in
x=$1
op=$2 true
y=$3 $
if [ $x $op $y ]; then
$ sh test_cmd_str.sh in != out
echo "true"
true
else
echo "false" $
fi
$ sh test_cmd_str.sh
www.opengurukul.com in != in 48
49. Shell Scripting: Test Command : Files
The test command can also be used to figure out the file type.
File Exists -e file
Normal File (Not a directory) -f file
Directory -d file
Symbolic Link -h file
Pipe -p file
Character Device File -c file
Block Device File -b file
Socket File -S file
Writable -w file
Readable -r file
Executable -x file
Non-Empty file -s file
www.opengurukul.com 49
50. Shell Scripting: Test Command : Files :
Example
Program : Output :
# example : test_cmd_file.sh
file=$1
$ sh test_cmd_file.sh
/bin/bash
if [ -d $file ] ; then
/bin/bash is a regular file
echo "$file is a directory"
$
elif [ -f $file ] ; then
echo "$file is a regular file"
else $ sh test_cmd_file.sh /home
echo "$file type not known"; /home is a directory
fi
$
www.opengurukul.com 50
51. Shell Scripting: Test Command : Logical
Operators
NOT ! expr
AND expr1 -a expr2
OR expr1 -o expr2
www.opengurukul.com 51
52. Shell Scripting: Test Command : Logical
Operators : Example
Program: Output :
# example:
test_cmd_logical.sh
$ sh test_cmd_logical.sh 5 4 3
5 is biggest
x=$1
$
y=$2
z=$3
# if test $x -lt $y
if [ $x -gt $y -a $x -gt $z ];www.opengurukul.com
then 52
54. Shell Scripting: Control Structures : if
construct
The format of if else fi is.
if test condition1
then
List of commands1
elif test condition2
then
List of commands2
elif test condition3
then
List of commands3 www.opengurukul.com 54
else
55. Shell Scripting: Control Structures : if
example
Program : Output :
# example : if_construct.sh $ sh if_construct.sh /var
/var: found
file=$1 $
if [ -e $file ]
then $ sh if_construct.sh /not
echo "$file: found" /not: not found
else $
www.opengurukul.com 55
echo "$file: not found"
56. Shell Scripting: Control Structures: while
The While...Do has the following generic form:
while test condtion
do
series of commands
done
www.opengurukul.com 56
57. Shell Scripting: Control Structures: while :
example
Program : Output :
# example : while_construct.sh
K=$1 $ sh while_construct.sh 5 9
LIMIT=$2 5
6
while test $K -le $LIMIT
7
do
8
echo "$K"
K=$(( K + 1 )) 9
done $
www.opengurukul.com 57
58. Shell Scripting: Control Structures: for
The syntax of the for command is:
for variable in list of values
do
list of commands
done
www.opengurukul.com 58
59. Shell Scripting: Control Structures: for :
Example
Program : Output :
# example : for_loop.sh
for K in 20 40 60 $ sh for_loop.sh
do
20
echo $K
40
done
60
for file in `ls /etc/*.ini` /etc/odbc.ini
do /etc/odbcinst.ini
echo $file /etc/php.ini
done $
www.opengurukul.com 59
60. Shell Scripting: Control Structures : case
The case construct has the following syntax:
case word in
pattern)
list of commands
;;
pattern)
list of commands
;;
*)
list of commands
;;
www.opengurukul.com 60
esac
61. Shell Scripting: Control Structures : case :
example
Program : Output :
# example : case_stmt.sh
$ sh case_stmt.sh 1
rank=$1
first
case $rank in
$
1) echo "first"
;; $ sh case_stmt.sh 2
2) echo "second" second
;; $
*) echo "invalid input"
$ sh case_stmt.sh 5
;; www.opengurukul.com 61
invalid input
esac
63. Shell Scripting: Functions
The syntax of an Shell function is defined as follows:
name ()
{
commands
...
commands
}
A function can be used to perform task that gets repeated multiple
times in shell script.
A function will return with a default exit status of zero, one can return
different exit status' by using the notation return exit status.
Variables can be defined locally within a function using local
name=value.
www.opengurukul.com 63
64. Shell Scripting: Functions : Example
Program : Output :
# example : func_sum.sh $ sh func_sum.sh
sum is : 3
sum() { $
result=`expr $1 + $2`
echo "sum is : " $result
}
www.opengurukul.com 64
65. Shell Scripting: Functions : Scope of
Variables
There is no scoping in Shell Scripts.
The scope applies only to arguments to Shell Script and arguments to
functions.
The arguments to both Shell Script and Functions are referred to as $1, $2, ...
etc.
$0 universally stores Shell Script Name.
$1
within a function represents first argument to function.
In a global scope (outside functions) represent first argument to Shell
Script.
$2
within a function represents second argument to function
In a global scope (outside functions) represent second argument to
Script.
www.opengurukul.com 65
So on...
67. Shell Scripting: Functions : List of Functions
We can get list of functions that are Output :
available in the current context in
bash using 'declare -f'
Program : $ sh func_declare.sh
$ cat func_declare.sh msg ()
# example : func_declare.sh {
msg() { echo "hello world"
echo "hello world" }
}
$
declare -f
$
www.opengurukul.com 67
69. Shell Scripting: Debugging
-v
The shell write its input to standard error as it is read.
-x
The shell shall write to standard error a trace for each command
after it expands the command and before it executes it.
www.opengurukul.com 69
70. Shell Scripting: Debugging
For small scripts
$ sh -x script_name
For huge scripts
$ sh -x script_name > /tmp/script_out.txt 2>&1
www.opengurukul.com 70
71. Shell Scripting: Debugging : Example
Program : Debug :
# example : debug.sh $ sh -v -x debug.sh
a=$1 a=$1
+ a=
b=$2
b=$2
c=`expr $a+$b`
Run: + b=
echo $c
$ sh debug.sh
expr: syntax error c=`expr $a+$b`
expr $a+$b
$ ++ expr
www.opengurukul.com + 71
72. Support
Please register yourself
@
www.opengurukul.com
In case you need any support in future.
www.opengurukul.com 72