Intro to Shell Scripting Basics
Intro to Shell Scripting Basics
[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: 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
[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>)
[Link] 17
File and Directory Management
[Link] 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
[Link] 19
Shell Scripting
[Link] 20
My First Shell Script
$ vi [Link]
#!/bin/sh
#Thefirstexampleofashellscript
directory=`pwd`
echoHelloWorld!
echoThedatetodayis`date`
echoThecurrentdirectoryis$directory
$ chmod +x [Link]
$ ./[Link]
HelloWorld!
ThedatetodayisMonMar[Link]ST2010
Thecurrentdirectoryis/netscr/shubin/test
[Link] 21
Shell Scripts
[Link] 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
[Link] 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`
[Link] 24
Echo
[Link] 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.
[Link] 27
Debugging your shell scripts
[Link] 28
Shell Programming
[Link] 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
[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
$ echo $SHELL
To see a list of your environment variables:
$ printenv
or:
$ printenv|more
[Link] 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 =
[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=(123)
echo${a[*]}
echo${a[0]}
Results: 123
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 : ./myscriptonetwobucklemyshoe
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
echoTotalnumberofinputs:$#
echoFirstinput:$1
echoSecondinput:$2
[Link] 37
Shell Programming
[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=`echoscale=2;$a+$b|bc`
echo$c
chmod u+x [Link]
./[Link]
15.80
[Link] 44
Arithmetic operations in
shell scripts
[Link] 45
Shell Programming
[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 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.
[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 Its Friday, its home time!!!
fi
[Link] 51
File enquiry operations
[Link] 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
[Link] 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
[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:
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
[Link] 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.
[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
[Link] 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
[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
Pleasedirect
directcomments/questions
comments/questionsabout
aboutresearch
researchcomputing
computingtoto
E-mail:
E-mail:research@[Link]
research@[Link]
Please
Pleasedirect
directcomments/questions
comments/questionspertaining
pertainingtotothis
thispresentation
presentationtoto
E-Mail:
E-Mail:shubin@[Link]
shubin@[Link]
[Link]
Hands-on Exercises