Objectives| Introduction| The Basics of Shell Programming| Shell Comments| Using Shell Variables| Predefined Shell Variables| Repeated Action Commands| Some Other Useful Commands| Conclusion| Review Questions
A shell program is executed by the appropriate shell reading the commands in the program one at a time and executing the commands almost exactly as if you were typing them in one at a time.
For example:
All shell programs in this course will use the syntax of the Bourne shell.
For example:
#!/bin/sh for the Bourne shell #!/bin/csh for the C shell
For example:
Exercise 3-2. Create a shell procedure called d that displays the message The current directory is /home/temp and it contains and on the following line displays the output of the ls command on the current directory.
A UNIX command will always have an executable program stored as a file somewhere on the disk. Try the command which commandname. This command searches through the current path for an executable program called commandname.
The code to perform a shell command is built into the shell program and won't be stored in a file.
Comments are especially important when any shell programs you write as a System Administrator are likely to have to be understood and maintained by a fellow administrator in a few years time.
Shell programs use the # character to signify comments. Anything after a # character until the end of the line is considered a comment and is ignored by the shell.
As an administrator you should choose a format for all the shell programs you and anyone else on the administration team will write.
For example:
# NAME: test_shell # AUTHOR: David Jones # PURPOSE: Demonstration of comment style # HISTORY: 19/05/94 Created # 25/05/94 Modified to show mods ls | more
Most programming languages have rules that restrict the format of variable names. For the Bourne shell, variable names must start with either a letter or an underscore character. It can then be followed by zero or more letters, numbers or underscores
To assign a value to a variable you use the following format
variable=value
(Remember this is the Bourne shell syntax. Using the C shell the format would be
set variable=value)
For example:
For example:
For example:
First attempt
Exercise 3-3 Which of the following are valid shell variable names.
a) temp b) temp.doc c) 1abc d) abc#1 e) abc_1_ f) TeMpVaR
Table 3.1. lists some of the shell variables typically set for a user's environment (there are numerous others).
Variable Purpose
HOME your home or login directory PS1 PS2 your first and second command prompts SHELL your current shell UID your user id USER your username TERM the type of terminal you logged in on DISPLAY your X-Windows display (if X is being used) PATH Your execution path Table 3.1. Environment Shell Variables.
For example:
Predefined Shell Variable Purpose $0 the name of the shell procedure being executed $1 thru $9 the first through ninth parameter passed to the shell program (see shift) $# the number of parameters passed $* used to represent all the parameters passed $$ contains the process id number of the current process, often used to create unique temporary files $? used to hold the exit status of the last command, a value of 0 means the last command succeeded, 1 means it failed "$@" used to represent all the parameters passed, especially if the parameters contain spaces, must use the surrounding "" Table 3.2. Predefined Shell Variables (Bourne Shell)Exercise 3-5. Write a shell program called arguments that tells the user how many command line arguments were passed to it and what they are.
Your shell program should use shell variables wherever possible.
Instead you must use the shell command shift. shift moves all the parameters one parameter to the left i.e. the first parameter disappears, the second parameter becomes the first, the third the second and so on. So after executing the shift command the tenth parameter has become the ninth parameter.
For example:
exit Command Format. exit number number should be 0 if the shell procedure succeeded. Any other value indicates failure. Figure 3.1. The exit Command.In a Bourne shell program the predefined variable $* is used to hold the exit status of the last command executed.
For example:
if Command Format. if commandt then command-list fi if commandt then command-list1 elif command1 command-list2 fi command-list is a list of 1 or more UNIX commands. commandt is any UNIX command. Figure 3.2. The if Command.The main difference with the UNIX if is that it waits on the outcome of a UNIX command.
For example:
if grep -s $1 /etc/passwd then echo user $1 was found in password file else echo user $1 NOT FOUND fi
case Command Format. case value in pat1) command command;; pat2) command-list;; *) command-list;; esac Figure 3.3. case Command Format.value is compared against each of the patterns signified by pat1.. one by one. If there is a match then the command list associated with that pattern is executed. The ;; symbol is used to signify the end of a command list for a particular pattern.
Once the end of the appropriate command list is reached, execution is restarted at the command directly after the esac. Only the first pattern matched will ever be executed.
The * pattern is optional and is used to match any value and so it acts as the default. (The * should never be the first choice. * matches everything and so the other choices will never get a look in.)
The * is an example of using wildcard characters in the patterns. You can also use the ? and [] wildcard symbols in the patterns. The | symbol can be used as an OR operator for patterns. i.e. pat1 | pat2 will be matched if at least one pattern is a match
For example:
case $1 in hello ) echo hello there;; goodbye ) echo why goodbye echo you haven't said hello;; T* | *T) echo that word started or ended with a T;; [a-z]?) echo that word started with a echo lowercase letter and was echo two letters long;; *) echo sorry I don't know that word;; esac case $# in 0) echo no parameters;; 1) echo one parameter;; 2) echo two parameters;; 3) echo three parameters;; esac
test Command Format. test expr [ expr ] The [ is actually the name of an executable program (Try the command which [ or whereis [). When it is executed you are actually running the program called test. Figure 3.4. test Command Format.The symbol expr can be one of the many expressions understood by the test command. test recognises expressions that test for the existence of files, compare the values of integers, compares strings etc. Tables 3.4-3.7 provide a sample of some of the available formats of expr.
Expression Result -z string true if the length of string is 0 -n string true if the length of string is not zero string1 = string2 true if the two strings are identical string1 != string2 true if the two strings are NOT identical string true if string is NOT the null string Table 3.4. Expressions for testing String Conditions
Expression Result int1 -eq int2 true if the two integers are equal int1 -ne int2 true if the two integers are not equal int1 -gt int2 true if int1 is greater than int2 int1 -ge int2 true if int1 is greater than or equal to int2 int1 -lt int2 true if int1 is less than int2 int1 -le int2 true if int1 is less than or equal to int2 Table 3.5. Expressions for testing Integer Conditions.
Expression Result -r file true if file exists and is readable -w file true if file exists and is writable -x file true if file exists and is executable -f file true if file exists and is a regular file, or true if file exists and is not a directory -d file true if file exists and is a directory -h file true if file exists and is a symbolic link -c file true if file exists and is a character special file -b file true if file exists and is a block special file -p file true if file exists and is a named pipe -u file true if file exists and its set user ID bit is set -g file true if file exists and its set group ID bit is set -k file true if file exists and its sticky bit is set -s file true if file exists and has a size greater than 0 Table 3.6. Expressions for testing File Conditions.
Expression Result ! the unary negation operator, reverses the result of an expression -a binary AND operator -o binary OR operator ( expr ) parentheses used for grouping, parentheses have special meaning to the shell so to use them in the test command you must quote them Table 3.7. Logical Operators.
if test $1 = hello then echo hello there fiIf the first parameter is greater than or equal to the second value (and both are integers) display an appropriate message.
if [ $1 -gt $2 -o $1 -eq $2 ] then echo $1 is greater than or equal to $2 fiIf there are no parameters to this shell procedure display the appropriate message.
if [ $# -eq 0 ] then echo You didn\'t enter any parameters fiExercise 3-6. Rewrite the shell program arguments from exercise 3.5. so that it tests to see if there were any command line arguments. If there weren't any it should display the message No parameters passed. Otherwise it should carry out the actions specified in exercise 3.5.
Exercise 3-7. Write a shell program exists that takes a filename as a command line parameters. If there are no command line parameters it should display a message explaining how to use it. If there are parameters it should test to see if a file with that name exists and display an appropriate message.
For example:
exists /etc/passwd
The file /etc/passwd exists.
for Command Format. for variable in word1 word2 word3 ... wordn do command-list done Figure 3.5. for Command Format.variable will take on each value in the list word1 word2 word3 ... wordn one value at a time. For each value the commands in command-list will be executed.
For example:
count=0 for param in $* # for every parameter do count=`expr $count + 1` # expr talked about later echo parameter $count is $param # display the number parameter and its value done echo days of the week are for today in sun mon tue wed thu fri sat do echo $today doneExercise 3-8. Modify the shell procedure exists written for exercise 3.7 so that it allows the user to enter multiple filenames.
while Command Format. while command1 do command-list done Figure 3.6. while Command Format.command1 is executed and if its exit status is true then the command-list is executed. This is repeated until command1 returns a false exit status.
For example:
display a countdown from 10 to 0 count=10 while [ $count -ge 0 ] do echo $count count=`expr $count - 1` done
until Command Format. until command1 do command-list done Figure 3.7. until Command Format.command1 is executed and while it returns an exit status of FALSE the command-list is executed. This continues until command1 returns an exit status of TRUE.
For example:
display a countdown from 10 to 0 count=10 until [ $count -lt 0 ] do echo $count count=`expr $count - 1` done
Command Purpose expr evaluates logical and arithmetic expressions cut used to extract fields of data from the lines of a file or the output of a command sort sorts its standard input into order head display the first X number of lines of standard input tail display the last X number of lines of standard output file attempts to describe the type of a file grep search for lines containing a character string uniq remove duplicated lines from standard input strings displays any ASCII characters contained in a binary file tr translates specified character(s) into other character(s) paste the opposite to cut, puts lines back together Table 3.8. Some other useful commands.
expr 5 + 6 expr 5 \* 10 + 5 echo "105 - 5 = " `expr 105 \- 5` cut -d: -f1,6 /etc/passwd cut -c1-8 /etc/passwd cut -d: -f1 /etc/passwd t -d: -f1 /etc/passwd | sort cat /etc/group sort /etc/group sort -r /etc/group cut -d: -f1,6 /etc/passwd | tr : ' ' cut -d: -f1 /etc/passwd | tr [a-z] [A-Z]
bash$ my_sum 1 2 3 4 5 Total = 153.2. Modify the my_sum shell script so that it produces output resembling the following.
csh> my_sum 1 2 3 4 5 1 + 2 + 3 + 4 + 5 = 153.3. Write a shell script called file_type that accepts as parameters the names of files. The script should decide what type of file the file is and inform the user. The shell script should display a help message if no parameters were passed and be able to handle multiple filenames as input.
David Jones (author)