UNIX Shell Scripting
UNIX Shell Scripting
Ken Steube
UCSD Extension
[email protected]
This course will teach you to write Bourne shell Scripts. We will then learn about C shell
scripts, and will have a brief introduction to perl as well. Scripting skills have many
applications, including:
Table of Contents:
1.
2.
3.
4.
5.
6.
Variables
The quotes are required in the example above because the string contains a special
character (the space)
A variable may store a number
num=137
Try defining num as '7m8' and try the expr command again
What happens when num is not a valid number?
Now you may exit the Bourne shell with
exit
Page 1
I/O Redirection
You can save the output of wc (or any other command) with output redirection
wc /etc/passwd > wc.file
Page 2
Backquotes
(To save the file, position the mouse over the the highlighted file name above and
press the right mouse button for a menu. Select "Save link as".)
Execute the script with
sh backquotes.sh
Backquotes are very useful, but be aware that they slow down a script
Page 3
Pipes
head -5 /etc/passwd
head -5 < /etc/passwd
You could accomplish the same thing more efficiently with either of the two
commands:
Page 4
awk
A more complicated example shows how to sum the file sizes and print the result
at the end of the awk run
Page 5
Shell Scripts
Topics covered: storing commands in a file and executing the file, $USER
variable (standard Bourne shell variable)
Utilities covered: date, cal, last, pipes
Store the following in a file named simple.sh and execute it
#!/bin/sh
# Generate some useful info for
# use at the start of the day
date
cal
last $USER | head -6
Shows current date, calendar, and a six of your previous logins for security check
You might run this at the beginning of each day
Notice that the commands themselves are not displayed, only the results
To display the commands verbatim as they run, execute with
sh -v simple.sh
With -v or -x (or both) you can easily relate any error message that may appear to
the command that generated it
When an error occurs in a script, the script continues executing at the next
command
Verify this by changing 'cal' to 'caal' to force an error, and then run the script again
Run the 'caal' script with 'sh -v simple.sh' and 'sh -x simple.sh' and verify the error
message comes from cal
Now you can re-use commands easily and save some typing and mistakes
Other standard variable names include: HOME, PATH, TERM, PAGER,
PRINTER
Page 6
#!/bin/sh
# An example with variables
filename="/etc/passwd"
echo "Check the permissions on $filename"
ls -l $filename
echo "Find out how many accounts there are on this system"
wc -l $filename
Topics covered: global search and replace, input and output redirection
Utilities covered: sed
Copy the file nlanr.txt to your home directory
Change 'platform' to 'computer' with
sed -e 's/platform/computer/g' < nlanr.txt
Performing Arithmetic
Topics covered: integer arithmetic, preceding '*' with backslash to avoid file
name wildcard expansion
Utilities covered: expr
Arithmetic is done with expr
expr 5 + 7
expr 5 \* 7
Page 9
Translating Characters
Topics covered: converting one character to another, translating and saving string
stored in a variable
Utilities covered: tr
Copy the file sdsc.txt to your home directory
The utility tr translates characters
tr 'a' 'Z' < sdsc.txt
This example shows how to translate the contents of a variable and display the
result on the screen with tr
Store the following in a file named tr1.sh and execute it
#!/bin/sh
# Translate the contents of a variable
Cat_name="Piewacket"
echo $Cat_name | tr 'a' 'i'
Now you can change the value of the variable and your script has access to the
new value
Page 10
#!/bin/sh
# Execute ls and wc on each of several files
# File names listed using file name wildcards
for filename in *.sh
do
echo "Variable filename is set to $filename..."
ls -l $filename
wc -l $filename
done
Should see three lines of output for each file name ending in '.sh'
Instead of listing files explicitly, uses file name wildcard to describe file names
Page 12
Topics covered: combining for loops with utilities for global search and replace
in several files
Utilities covered: mv
Store the following in a file named s-and-r.sh and execute it
#!/bin/sh
# Perform a global search and replace on each of several files
# File names listed explicitly
for text_file in sdsc.txt nlanr.txt
do
echo "Editing file $text_file"
sed -e 's/application/APPLICATION/g' $text_file > temp
mv -f temp $text_file
done
Sed cannot overwrite source file, so must use temp file + mv:
Sed performs global search and replace
Saves new result in file 'temp'
Mv overwrites old file with new data
Page 13
(an option)
(a file name)
(a directory name)
The command above has an unknown number of arguments, use 'echo *.sh' to see
them
Your scripts may also have arguments
Page 15
This script runs properly with any number of arguments, including zero
Shorter form of the same loop
for filename
...
Don't use
for filename in $*
If Blocks
Page 19
Regular Expressions
Page 21
Eagerness: a regular expression will find the first match if several are present in
the line
Execute this command and see whether 'big' or 'bag' is matched by the regular
expression
echo 'big bag' | sed -e 's/b.g/___/'
Hint: a* matches zero or more a's, and there are many places where zero a's
appear
Try the example above with the extra 'g'
echo 'black dog' | sed -e 's/a*/_/g'
Page 22
regexp
wildcard
meaning
.*
.
[aCg]
*
?
[aCg]
Page 23
Page 24
;;
list)
echo "Running ls..."
ls
;;
cal)
echo "Running cal..."
cal
;;
*)
echo "Bad command, your choices are: who, list, or cal"
;;
esac
exit 0
The last case above is the default, which corresponds to an unrecognized entry
The next example uses the first command-line arg instead of asking the user to
type a command
Store the following in a file named case2.sh and execute it
#!/bin/sh
# An example with the case statement
# Reads a command from the user and processes it
# Execute with one of
# sh case2.sh who
# sh case2.sh ls
# sh case2.sh cal
echo "Took command from the argument list: '$1'"
case "$1" in
who)
echo "Running who..."
who
;;
list)
echo "Running ls..."
ls
;;
cal)
echo "Running cal..."
cal
;;
*)
echo "Bad command, your choices are: who, list, or cal"
;;
esac
The patterns in the case statement may use file name wildcards
Page 25
Page 26
The entire while loop reads its stdin from the pipe
Each read command reads another line from the file coming from cat
The entire while loop runs in a subshell because of the pipe
Variable values set inside while loop not available after while loop
Page 27
Functions
Define a Function
Define a function
echo_it () {
echo "In function echo_it"
}
Function Arguments
#!/bin/sh
echo_it () {
echo Function argument 1 is $1
}
echo Script argument 1 is $1
echo_it Barney
Page 33
Functions in Pipes
Inherited Variables
Try it: is a variable defined inside a function available to the main program?
Page 35
Operate in pipes
echo "test string" | ls_sorter
Page 36
Libraries of Functions
Section 7: Miscellaneous
Here Files
Common Signals
Page 44
Send a Signal
Page 45
Trap Signals
Handling Signals
trap "echo Interrupted; exit 2" 2
Ignoring Signals
trap "" 2 3
Page 46
See file
/usr/include/sys/signal.h
Page 47
User Signals
Command Translation
Order of Translations
Echos command if -v
Interprets quotes
Performs variable substitution
Page 52
Exceptional Case
Page 55
Examples (continued)
x=*
echo $x
Examples (continued)
Wildcards expanded after redirection (assuming file* matches exactly one file):
cat < file*
file*: No such file or directory
Page 57
Eval Command
While loops
Page 59
Until loops
Page 60
Redirection of Loops
Continue Command
Break Command
Exit loop
for name in *
do
if [ ! -r $name ] ; then
echo "Cannot read $name, quitting loop"
break
fi
echo "Found file or directory $name"
done
Example loops over files and directories, quits if one is not readable
Page 63
Case Command
Page 64
When you run it, the script waits for you to type one of:
list
freespace
quit
Quit
Try it: modify the example so any command beginning with characters "free" runs
df
Page 65
Infinite Loops
Remote Shells
Rsh command
rsh hostname "commands"
Page 67
Page 70
Return Status
Temporary Files
tempfile=$HOME/Weq_$$
command > $tempfile
Wait Command
Quotes
$HOME'
Home:
$HOME
Page 75
Metacharacters
Page 76
Page 78
Page 79
Last modified: Saturday, May 24, 2008 12:29:11 AM
Last modified: Wed 15 Aug 2007 11:17:36 AM EDT
Last modified: Tue 10 Dec 2002 06:48:21 AM EST