Introduction to Shell Scripting Basics
Introduction to Shell Scripting Basics
[Link] 2
Objectives & Prerequisites
[Link] 6
What is a “Shell”?
user
Shell
▪ How to know what shell you use
echo $SHELL
user OS
user
[Link] 7
UNIX Shells
[Link] 10
A Shell Script Example
#!/bin/sh
done
/bin/rm ./junk ./head ./file_list
[Link] 11
UNIX/LINUX Commands
[Link] 12
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] 13
File and Directory Management
[Link] 14
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
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] 18
Shell Scripting
[Link] 19
My First Shell Script
$ vi [Link]
#! /bin/sh
[Link] 20
Shell Scripts
[Link] 21
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] 22
Quote Characters
[Link] 25
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] 26
Debugging your shell scripts
[Link] 27
Shell Programming
[Link] 28
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] 29
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] 31
Defining Local Variables
[Link] 33
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] 34
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] 35
Variables
▪ vi [Link]
#! /bin/sh
echo Total number of inputs: $#
echo First input: $1
echo Second input: $2
[Link] 36
Shell Programming
[Link] 37
Shell Operators
[Link] 38
Defining and Evaluating
[Link] 39
Linux Commands
Pipes & Redirecting
[Link] 40
Arithmetic Operators
[Link] 41
Arithmetic Operators
▪ vi [Link]
#!/bin/sh
count=5
count=`expr $count + 1 `
echo $count
▪ chmod u+x [Link]
▪ [Link]
6
[Link] 42
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] 43
Arithmetic operations in
shell scripts
[Link] 44
Shell Programming
[Link] 45
Shell Logic Structures
[Link] 46
Conditional Statements
(if constructs )
[Link] 47
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] 48
Tests
[Link] 49
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] 50
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] 52
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] 53
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] 54
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] 55
The while Loop
[Link] 56
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] 57
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] 58
until loops
[Link] 59
Switch/Case Logic
[Link] 60
Case statements
sum 5 3
echo "The sum of 4 and 7 is `sum 4 7`"
[Link] 62
Take-Home Message
[Link] 63
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] 64
Shell Scripting Examples
[Link] 65
Input file preparation
#!/bin/sh
done
/bin/rm ./junk ./head ./file_list
[Link] 66
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] 67
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] 68
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] 69
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