Shell - Scripting For Unix and Linux Operating System
Shell - Scripting For Unix and Linux Operating System
user OS
user
UNIX Shells
• sh Bourne Shell (Original Shell) (Steven Bourne of
AT&T)
• bash Bourne Again Shell (GNU Improved Bourne
Shell)
• csh C-Shell (C-like Syntax)(Bill Joy of Univ. of
California)
• ksh Korn-Shell (Bourne+some C-shell)(David Korn
of AT&T)
• tcsh Turbo C-Shell (More User Friendly C-Shell).
• To check shell:
o $ echo $SHELL (shell is a pre-defined variable)
What is Shell Script?
• A shell script is a script written for the shell
done
/bin/rm ./junk ./head ./file_list
UNIX/LINUX
Commands
• File Management and Viewing • To understand the working of the
command and possible options
• Filesystem Mangement use (man command)
• Help,Job/Process
• Using the GNU Info System
Management
(info, info command)
• Network Management
• Listing a Description of a Program
• System Management
(whatis command)
• User Management
• Many tools have a long−style
• Printing and Programming option, `−−help', that outputs
• Document Preparation usage information about the tool,
• Miscellaneous including the options and
arguments the tool takes. Ex:
whoami --help
File/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
File/Directory
Management
• ls List contents of a directory.
Ex: ls, ls –l , ls –al, ls –ld, ls –R
• mkdir Make a directory.
Ex: mkdir <directory name> : Makes a directory
Ex mkdir –p /www/chache/var/log will create all the directories starting from www.
• mv Move or rename a file or directory.
Ex: mv <source> <destination>
• find Find files (find <start directory> -name <file name> -print)
Ex: find /home –name readme -print
Search for readme starting at home and output full path, “/home" = Search starting at the
home directory and proceed through all its subdirectories; "-name readme" = Search
for a file named readme "-print" = Output the full path to that file
• locate File locating program that uses the locate database.
Ex: locate –u to create the database,
locate <file/directory> to find file/directory
File/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>)
$ echo $SHELL
To see a list of your environment variables:
$ printenv
or:
$ printenv | more
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=abc def # will not work unless ‘quoted’
b=‘abc def’ # i.e. this will work.
IMPORTANT NOTE: DO NOT LEAVE SPACES AROUND THE =
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
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
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.
Variables
• vi myinputs.sh
#! /bin/sh
echo Total number of inputs: $#
echo First input: $1
echo Second input: $2
EXAMPLE:
while test "$i" -gt 0 # can also be while [ $i
>0]
do
i=`expr $i - 1`
done
Looping Logic
• Example: ▪ Adding integers from 1 to 10
#!/bin/sh #!/bin/sh
for person in Bob Susan Joe Gerry
do i=1
echo Hello $person sum=0
done
while [ “$i” -le 10 ]
Output: do
Hello Bob echo Adding $i into the
Hello Susan sum.
Hello Joe sum=`expr $sum + $i `
Hello Gerry
i=`expr $i + 1 `
done
echo The sum is $sum.
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
Switch/Case
Logic
• The switch logic structure simplifies the
selection of a match when you have a list of
choices
sum 5 3
echo "The sum of 4 and 7 is `sum 4 7`"
Read Write in Files
• Shell script can also work with files. We can read and write
into any file easily.
• With catting a file and piping the file output to a while read
loop a
single line of text is read into a variable named LINE on
each loop
iteration.
• This continuous loop will run until all of the lines in the
file have been processed one at a time.
Read write in
Files(Cont.)
• #!/bin/bash
# SCRIPT: method1.sh
# PURPOSE: Process a file line by line with PIPED while-read
loop.
FILENAME=$1
count=0
cat $FILENAME | while read LINE
do
let count++
echo "$count $LINE"
done
• Cons
o Performance slowdown
o Accurate scientific computing
•
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-bur
tch-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
Questions & Comments
its.unc.ed
Hands-on Exercises
1. The simplest Hello World shell script – Echo command
2. Summation of two integers – If block
3. Summation of two real numbers – bc (basic calculator)
command
4. Script to find out the biggest number in 3 numbers – If –elif
block
5. Operation (summation, subtraction, multiplication and division)
of two numbers – Switch
6. Script to reverse a given number – While block
7. A more complicated greeting shell script
8. Sort the given five numbers in ascending order (using array) –
Do loop and array
9. Calculating average of given numbers on command line
arguments – Do loop
10. Calculating factorial of a given number – While block
11. An application in research computing – Combining all above
12. Optional: Write own shell scripts for your own purposes if time
permits
Thank You…
☺
its.unc.ed