Shell Scripting
Shell Scripting
Santosh Kumar
Assistant Professor
AI&DS Department, VIIT, Pune
[Link]@[Link]
Contents
▪ Introduction
• UNIX/LINUX and Shell
• UNIX Commands and Utilities
• Basic Shell Scripting Structure
▪ Shell Programming
• Variable
• Operators
• Logic Structures
▪ Examples of Application in Cloud & Devops
▪ Hands-on Exercises
[Link] 2
Why Shell Scripting ?
[Link] 3
Objectives & Prerequisites
[Link] 7
What is a “Shell”?
user
[Link] 8
UNIX Shells
[Link] 11
A Shell Script Example
#!/bin/sh
done
/bin/rm ./junk ./head ./file_list
[Link] 12
UNIX/LINUX Commands
[Link] 13
File and Directory Management
• cd Change the current directory. With no arguments "cd" changes to the users home
directory. (cd <directory path>)
• chmod Change the file permissions.
Ex: chmod 751 myfile : change the file permissions to rwx for owner, rx for group and
x for others (x=1,r=4,w=2)
Ex: chmod go=+r myfile : Add read permission for the group and others (character
meanings u-user, g-group, o-other, + add permission,-remove,r-read,w-write,x-exe)
Ex: chmod +s myfile - Setuid bit on the file which allows the program to run with
user or group privileges of the file.
• chown Change owner.
Ex: chown <owner1> <filename> : Change ownership of a file to owner1.
• chgrp Change group.
Ex: chgrp <group1> <filename> : Change group of a file to group1.
• cp Copy a file from one location to another.
Ex: cp file1 file2 : Copy file1 to file2; Ex: cp –R dir1 dir2 : Copy dir1 to dir2
[Link] 14
File and Directory Management
[Link] 15
File and Directory Management
• pwd Print or list the present working directory with full path.
• rm Delete files (Remove files). (rm –rf <directory/file>)
• rmdir Remove a directory. The directory must be empty. (rmdir <directory>)
• touch Change file timestamps to the current time. Make the file if it doesn't exist. (touch
<filename>)
• whereis Locate the binary and man page files for a command. (whereis
<program/command>)
• which Show full path of commands where given commands reside. (which <command>)
File viewing and editing
• emacs Full screen editor.
• pico Simple text editor.
• vi Editor with a command mode and text mode. Starts in command mode.
• gedit GUI Text Editor
• tail Look at the last 10 lines of a file.
Ex: tail –f <filename> ; Ex: tail -100 <filename>
• head Look at the first 10 lines of a file. (head <filename>)
[Link] 16
File and Directory Management
[Link] 18
Useful Commands in Scripting
▪ grep
• Pattern searching
• Example: grep ‘boo’ filename
▪ sed
• Text editing
• Example: sed 's/XYZ/xyz/g' filename
▪ awk
• Pattern scanning and processing
• Example: awk ‘{print $4, $7}’ filename
[Link] 19
Shell Scripting
[Link] 21
Shell Scripts
[Link] 22
Commenting
[Link] 26
Hello script exercise
continued…
▪ The following script asks the user to enter his
name and displays a personalised hello.
#!/bin/sh
echo “Who am I talking to?”
read user_name
echo “Hello $user_name”
▪ Try replacing “ with ‘ in the last line to see
what happens.
[Link] 27
Debugging your shell scripts
[Link] 28
Shell Programming
[Link] 29
Variables
• Local Variables
Within a shell script, you can create as many new variables as needed. Any variable
created in this manner remains in existence only within that shell.
• Special Variables
Reversed for OS, shell programming, etc. such as positional parameters $0, $1 …
[Link] 30
A few global (environment)
variables
SHELL Current shell
DISPLAY Used by X-Windows system to identify the
display
HOME Fully qualified name of your login directory
$ printenv
or:
$ printenv | more
[Link] 32
Defining Local Variables
[Link] 33
Referencing variables
--curly bracket
▪ Having defined a variable, its contents can be referenced by
the $ symbol. E.g. ${variable} or simply $variable. When
ambiguity exists $variable will not work. Use ${ } the
rigorous form to be on the safe side.
▪ Example:
a=‘abc’
b=${a}def # this would not have worked without the{ } as
#it would try to access a variable named adef
[Link] 34
Variable List/Arrary
▪ To create lists (array) – round bracket
$ set Y = (UNL 123 CS251)
▪ Example:
#!/bin/sh
a=(1 2 3)
echo ${a[*]}
echo ${a[0]}
Results: 1 2 3
1
[Link] 35
Positional Parameters
▪ When a shell script is invoked with a set of command line parameters each
of these parameters are copied into special variables that can be accessed.
▪ $0 This variable that contains the name of the script
▪ $1, $2, ….. $n 1st, 2nd 3rd command line parameter
▪ $# Number of command line parameters
▪ $$ process ID of the shell
▪ $@ same as $* but as a list one at a time (see for loops later )
▪ $? Return code ‘exit code’ of the last command
▪ Shift command: This shell command shifts the positional parameters by
one towards the beginning and drops $1 from the list. After a shift $2
becomes $1 , and so on … It is a useful command for processing the input
parameters one at a time.
Example:
Invoke : ./myscript one two buckle my shoe
During the execution of myscript variables $1 $2 $3 $4 and $5 will contain
the values one, two, buckle, my, shoe respectively.
[Link] 36
Variables
▪ vi [Link]
#! /bin/sh
echo Total number of inputs: $#
echo First input: $1
echo Second input: $2
[Link] 37
Shell Programming
<Shell variables
<Operators
<Logic structures
[Link] 38
Shell Operators
[Link] 39
Defining and Evaluating
[Link] 40
Linux Commands
Pipes & Redirecting
[Link] 41
Arithmetic Operators
[Link] 42
Arithmetic Operators
▪ vi [Link]
#!/bin/sh
count=5
count=`expr $count + 1 `
echo $count
▪ chmod u+x [Link]
▪ [Link]
6
[Link] 43
Arithmetic Operators
▪ vi [Link]
#!/bin/sh
a=5.48
b=10.32
c=`echo “scale=2; $a + $b” |bc`
echo $c
▪ chmod u+x [Link]
▪ ./[Link]
15.80
[Link] 44
Arithmetic operations in
shell scripts
[Link] 45
Shell Programming
<Shell variables
<Operators
<Logic structures
[Link] 46
Shell Logic Structures
[Link] 47
Conditional Statements
(if constructs )
The most general form of the if construct is;
[Link] 48
Examples
SIMPLE EXAMPLE:
if date | grep “Fri”
then
echo “It’s Friday!”
fi
FULL EXAMPLE:
if [ “$1” == “Monday” ]
then
echo “The typed argument is Monday.”
elif [ “$1” == “Tuesday” ]
then
echo “Typed argument is Tuesday”
else
echo “Typed argument is neither Monday nor Tuesday”
fi
# Note: = or == will both work in the test but == is better for readability.
[Link] 49
Tests
[Link] 50
Combining tests with logical
operators || (or) and && (and)
Syntax: if cond1 && cond2 || cond3 …
An alternative form is to use a compound statement using the –a
and –o keywords, i.e.
if cond1 –a cond22 –o cond3 …
Where cond1,2,3 .. Are either commands returning a a value or test
conditions of the form [ ] or test …
Examples:
if date | grep “Fri” && `date +’%H’` -gt 17
then
echo “It’s Friday, it’s home time!!!”
fi
if [ “$a” –lt 0 –o “$a” –gt 100 ] # note the spaces around ] and [
then
echo “ limits exceeded”
fi
[Link] 51
File enquiry operations
▪ A simple example
#!/bin/sh
if [ “$#” -ne 2 ] then
echo $0 needs two parameters!
echo You are inputting $# parameters.
else
par1=$1
par2=$2
fi
echo $par1
echo $par2
[Link] 53
Decision Logic
Another example:
#! /bin/sh
# number is positive, zero or negative
echo –e "enter a number:\c"
read number
if [ “$number” -lt 0 ]
then
echo "negative"
elif [ “$number” -eq 0 ]
then
echo zero
else
echo positive
fi
[Link] 54
Loops
Loop is a block of code that is repeated a number
of times.
The repeating is performed either a
pre-determined number of times determined by
a list of items in the loop count ( for loops ) or
until a particular condition is satisfied ( while
and until loops)
To provide flexibility to the loop constructs there
are also two statements namely break and
continue are provided.
[Link] 55
for loops
Syntax:
for arg in list
do
command(s)
...
done
Where the value of the variable arg is set to the values provided
in the list one at a time and the block of statements
executed. This is repeated until the list is exhausted.
Example:
for i in 3 2 5 7
do
echo " $i times 5 is $(( $i * 5 )) "
done
[Link] 56
The while Loop
[Link] 57
while loops
Syntax:
while this_command_execute_successfully
do
this command
and this command
done
EXAMPLE:
while test "$i" -gt 0 # can also be while [ $i > 0 ]
do
i=`expr $i - 1`
done
[Link] 58
Looping Logic
#!/bin/sh #!/bin/sh
for person in Bob Susan Joe Gerry i=1
do sum=0
echo Hello $person
while [ “$i” -le 10 ]
done
do
Output: echo Adding $i into the sum.
Hello Bob sum=`expr $sum + $i `
Hello Susan i=`expr $i + 1 `
Hello Joe done
Hello Gerry echo The sum is $sum.
[Link] 59
until loops
The syntax and usage is almost identical to the
while-loops.
Except that the block is executed until the test condition
is satisfied, which is the opposite of the effect of test
condition in while loops.
Note: You can think of until as equivalent to not_while
Syntax: until test
do
commands ….
done
[Link] 60
Switch/Case Logic
[Link] 61
Case statements
sum 5 3
echo "The sum of 4 and 7 is `sum 4 7`"
[Link] 63
Take-Home Message
▪ Pros
• File processing
• Glue together compelling, customized testing utilities
• Create powerful, tailor-made manufacturing tools
• Cross-platform support
• Custom testing and debugging
▪ Cons
• Performance slowdown
• Accurate scientific computing
[Link] 65
Shell Scripting Examples
[Link] 66
Input file preparation
#!/bin/sh
done
/bin/rm ./junk ./head ./file_list
[Link] 67
LSF Job Submission
$ vi [Link]
#!/bin/sh -f
#BSUB -q week
#BSUB -n 4
#BSUB -o output
#BSUB -J job_type
#BSUB -R “RH5 span[ptile=4]”
#BSUB -a mpichp4
[Link] ./[Link]
exit
$chmod +x [Link]
$bsub < [Link]
[Link] 68
Results Processing
#!/bin/sh
`ls -l *.out| awk '{print $8}'|sed 's/.out//g' > file_list`
cat file_list|while read each_file
do
file1=./$each_file".out"
Ts=`grep 'Kinetic energy =' $file1 |tail -n 1|awk '{print $4}' `
Tw=`grep 'Total Steric Energy:' $file1 |tail -n 1|awk '{print $4}' `
TsVne=`grep 'One electron energy =' $file1 |tail -n 1|awk '{print $5}' `
Vnn=`grep 'Nuclear repulsion energy' $file1 |tail -n 1|awk '{print $5}' `
J=`grep 'Coulomb energy =' $file1 |tail -n 1|awk '{print $4}' `
Ex=`grep 'Exchange energy =' $file1 |tail -n 1|awk '{print $4}' `
Ec=`grep 'Correlation energy =' $file1 |tail -n 1|awk '{print $4}' `
Etot=`grep 'Total DFT energy =' $file1 |tail -n 1|awk '{print $5}' `
HOMO=`grep 'Vector' $file1 | grep 'Occ=2.00'|tail -n 1|cut -c35-47|sed 's/D/E/g' `
orb=`grep 'Vector' $file1 | grep 'Occ=2.00'|tail -n 1|awk '{print $2}' `
orb=`expr $orb + 1 `
LUMO=`grep 'Vector' $file1 |grep 'Occ=0.00'|grep ' '$orb' ' |tail -n 1|cut -c35-47|sed
's/D/E/g'
echo $each_file $Etot $Ts $Tw $TsVne $J $Vnn $Ex $Ec $HOMO $LUMO $steric >>out
done
/bin/rm file_list
[Link] 69
Reference Books
▪ Class Shell Scripting
[Link]
▪ LINUX Shell Scripting With Bash
[Link]
[Link]
▪ Shell Script in C Shell
[Link]
▪ Linux Shell Scripting Tutorial
[Link]
▪ Bash Shell Programming in Linux
[Link]
▪ Advanced Bash-Scripting Guide
[Link]
▪ Unix Shell Programming
[Link]
[Link]
[Link] 70
Questions & Comments
Please direct comments/questions about research computing to
E-mail: research@[Link]
Please direct comments/questions pertaining to this presentation to
E-Mail: shubin@[Link]
[Link]
Hands-on Exercises