Shell Scripting
Shell Scripting
its.unc.edu 3
Objectives & Prerequisites
its.unc.edu 7
What is a Shell?
user
its.unc.edu 8
UNIX Shells
its.unc.edu 11
A Shell Script Example
#!/bin/sh
done
/bin/rm ./junk ./head ./file_list
its.unc.edu 12
UNIX/LINUX Commands
its.unc.edu 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: chmod751myfile : change the file permissions to rwx for owner, rx for group and
x for others (x=1,r=4,w=2)
Ex: chmodgo=+rmyfile : 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+smyfile - 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
its.unc.edu 14
File and Directory Management
its.unc.edu 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>)
its.unc.edu 17
File and Directory Management
its.unc.edu 18
Useful Commands in Scripting
grep
Pattern searching
Example: grepboofilename
sed
Text editing
Example: sed's/XYZ/xyz/g'filename
awk
Pattern scanning and processing
Example: awk{print$4,$7}filename
its.unc.edu 19
Shell Scripting
its.unc.edu 20
My First Shell Script
$ vi myfirstscript.sh
#!/bin/sh
#Thefirstexampleofashellscript
directory=`pwd`
echoHelloWorld!
echoThedatetodayis`date`
echoThecurrentdirectoryis$directory
$ chmod +x myfirstscript.sh
$ ./myfirstscript.sh
HelloWorld!
ThedatetodayisMonMar815:20:09EST2010
Thecurrentdirectoryis/netscr/shubin/test
its.unc.edu 21
Shell Scripts
its.unc.edu 22
Commenting
Lines starting with # are comments except the very first
line where #! indicates the location of the shell that will be
run to execute the script.
On any line characters following an unquoted # are
considered to be comments and ignored.
Comments are used to;
Identify who wrote it and when
Identify input variables
Make code easy to read
Explain complex code sections
Version control tracking
Record modifications
its.unc.edu 23
Quote Characters
There are three different quote characters with different
behaviour. These are:
: double quote, weak quote. If a string is enclosed in
the references to variables (i.e $variable ) are replaced by
their values. Also back-quote and escape \ characters are
treated specially.
: single quote, strong quote. Everything inside single quotes
are taken literally, nothing is treated as special.
` : back quote. A string enclosed as such is treated as a
command and the shell attempts to execute it. If the
execution is successful the primary output from the
command replaces the string.
Example: echoTodayis:`date`
its.unc.edu 24
Echo
its.unc.edu 26
Hello script exercise
continued
The following script asks the user to enter his
name and displays a personalised hello.
#!/bin/sh
echoWhoamItalkingto?
readuser_name
echoHello$user_name
Try replacing with in the last line to see
what happens.
its.unc.edu 27
Debugging your shell scripts
its.unc.edu 28
Shell Programming
its.unc.edu 29
Variables
When you login, there will be a large number of global System variables that are
already defined. These can be freely referenced and used in your shell scripts.
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
its.unc.edu 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
$ echo $SHELL
To see a list of your environment variables:
$ printenv
or:
$ printenv|more
its.unc.edu 32
Defining Local Variables
As in any other programming language, variables can be defined and
used in shell scripts.
Unlike other programming languages, variables in Shell Scripts are not
typed.
Examples :
a=1234 # a is NOT an integer, a string instead
b=$a+1 # will not perform arithmetic but be the string 1234+1
b=`expr$a+1` will perform arithmetic so b is 1235 now.
Note : +,-,/,*,**, % operators are available.
b=abcde # b is string
b=abcde # same as above but much safer.
b=abcdef # will not work unless quoted
b=abcdef # i.e. this will work.
IMPORTANT NOTE: DO NOT LEAVE SPACES AROUND THE =
its.unc.edu 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
its.unc.edu 34
Variable List/Arrary
To create lists (array) round bracket
$ set Y = (UNL 123 CS251)
Example:
#!/bin/sh
a=(123)
echo${a[*]}
echo${a[0]}
Results: 123
1
its.unc.edu 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 : ./myscriptonetwobucklemyshoe
During the execution of myscript variables $1 $2 $3 $4 and $5 will contain
the values one,two,buckle,my,shoe respectively.
its.unc.edu 36
Variables
vi myinputs.sh
#!/bin/sh
echoTotalnumberofinputs:$#
echoFirstinput:$1
echoSecondinput:$2
its.unc.edu 37
Shell Programming
its.unc.edu 38
Shell Operators
its.unc.edu 39
Defining and Evaluating
its.unc.edu 40
Linux Commands
Pipes & Redirecting
its.unc.edu 41
Arithmetic Operators
its.unc.edu 42
Arithmetic Operators
vi math.sh
#!/bin/sh
count=5
count=`expr$count+1`
echo$count
chmod u+x math.sh
math.sh
6
its.unc.edu 43
Arithmetic Operators
vi real.sh
#!/bin/sh
a=5.48
b=10.32
c=`echoscale=2;$a+$b|bc`
echo$c
chmod u+x real.sh
./real.sh
15.80
its.unc.edu 44
Arithmetic operations in
shell scripts
its.unc.edu 45
Shell Programming
its.unc.edu 46
Shell Logic Structures
its.unc.edu 47
Conditional Statements
(if constructs )
The most general form of the if construct is;
its.unc.edu 48
Examples
SIMPLE EXAMPLE:
if date | grep Fri
then
echo Its 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.
its.unc.edu 49
Tests
its.unc.edu 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 Its Friday, its home time!!!
fi
its.unc.edu 51
File enquiry operations
its.unc.edu 52
Decision Logic
A simple example
#!/bin/sh
if[$#ne2]then
echo$0needstwoparameters!
echoYouareinputting$#parameters.
else
par1=$1
par2=$2
fi
echo$par1
echo$par2
its.unc.edu 53
Decision Logic
Another example:
#!/bin/sh
#numberispositive,zeroornegative
echoe"enteranumber:\c"
readnumber
if[$numberlt0]
then
echo"negative"
elif[$numbereq0]
then
echozero
else
echopositive
fi
its.unc.edu 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.
its.unc.edu 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
its.unc.edu 56
The while Loop
its.unc.edu 57
while loops
Syntax:
whilethis_command_execute_successfully
do
thiscommand
andthiscommand
done
EXAMPLE:
while test "$i" -gt 0 # can also be while [ $i > 0 ]
do
i=`expr $i - 1`
done
its.unc.edu 58
Looping Logic
#!/bin/sh #!/bin/sh
forpersoninBobSusanJoeGerry i=1
do
sum=0
echoHello$person
while[$ile10]
done
do
Output: echoAdding$iintothesum.
HelloBob sum=`expr$sum+$i`
HelloSusan i=`expr$i+1`
HelloJoe done
HelloGerry echoThesumis$sum.
its.unc.edu 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
its.unc.edu 60
Switch/Case Logic
its.unc.edu 61
Case statements
sum 5 3
echo "The sum of 4 and 7 is `sum 4 7`"
its.unc.edu 63
Take-Home Message
its.unc.edu 64
To Script or Not to Script
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
its.unc.edu 65
Shell Scripting Examples
its.unc.edu 66
Input file preparation
#!/bin/sh
done
/bin/rm ./junk ./head ./file_list
its.unc.edu 67
LSF Job Submission
$ vi submission.sh
#!/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
mpirun.lsf ./executable.exe
exit
$chmod +x submission.sh
$bsub < submission.sh
its.unc.edu 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
its.unc.edu 69
Reference Books
Class Shell Scripting
http://oreilly.com/catalog/9780596005955/
LINUX Shell Scripting With Bash
http://ebooks.ebookmall.com/title/linux-shell-scripting-with-bash-burtch-
ebooks.htm
Shell Script in C Shell
http://www.grymoire.com/Unix/CshTop10.txt
Linux Shell Scripting Tutorial
http://www.freeos.com/guides/lsst/
Bash Shell Programming in Linux
http://www.arachnoid.com/linux/shell_programming.html
Advanced Bash-Scripting Guide
http://tldp.org/LDP/abs/html/
Unix Shell Programming
http://ebooks.ebookmall.com/title/unix-shell-programming-kochan-wood-
ebooks.htm
its.unc.edu 70
Questions & Comments
Please
Pleasedirect
directcomments/questions
comments/questionsabout
aboutresearch
researchcomputing
computingtoto
E-mail:
E-mail:research@unc.edu
research@unc.edu
Please
Pleasedirect
directcomments/questions
comments/questionspertaining
pertainingtotothis
thispresentation
presentationtoto
E-Mail:
E-Mail:shubin@email.unc.edu
shubin@email.unc.edu
its.unc.edu
Hands-on Exercises