|
UNIX Fundamentals
MODULE 8 – Shell scripts and Variables
You will cover
* Using UNIX variables
þ Using command substitution
þ Aliases in the Korn shell
þ Creating and running simple scripts
þ Simple menu construction
MODULE 8 – CONTENTS
8. INTRODUCTION TO SHELL PROGRAMS 4
8.1 EXECUTING SHELL PROGRAMS 4
8.2 ALTERNATIVE METHODS OF EXECUTION 5
8.3 LOCATION OF SHELL PROGRAMS 5
8.4 VARIABLES IN SHELL PROGRAMS 6
8.4.1 DIRECT ASSIGNMENT 6
8.4.2 EXPORTING VARIABLES 7
8.4.3 ASSIGNING VARIABLES WITH READ 8
8.4.4 COMMAND SUBSTITUTION 8
8.4.5 VARIABLE EXPANSION 9
8.4.6 VARIABLE EVALUATION 9
8.4.7 POSITIONAL VARIABLES 10
8.4.8 SYSTEM VARIABLES 11
8.4.9 VIEWING VARIABLES 12
8.5 CONTROL STRUCTURES IN SHELL PROGRAMS 13
8.5.1 CONDITIONAL STATEMENTS WITH IF 13
8.5.2 USING IF WITH TEST STATEMENTS 14
8.5.3 TESTING CONDITIONS WITH && AND || 17
8.6 PATTERN MATCHING WITH CASE STATEMENTS 18
8.7 REPEATED EXECUTIONS WITH FOR LOOPS 20
8.8 REPEATED EXECUTIONS WITH WHILE LOOPS 21
8.8.1 CONTINUOUS LOOPS WITH WHILE TRUE 21
8.8.2 BREAKING FROM LOOPS 22
8.9 OVERVIEW OF THE AWK UTILITY 23
8.9.1 FIELDS IN AWK 24
8.9.2 RELATIONAL EXPRESSIONS WITH AWK 25
8.9.3 BUILT IN AWK VARIABLES 26
8.9.4 USING AWK SCRIPTS 27
8.10 SIGNAL HANDLING WITH TRAP 29
8.11 REPLACING COMMANDS WITH ALIAS OR FUNCTION COMMANDS 30
8.11.1 USING ALIAS IN PROGRAMS 30
8.11.2 USING FUNCTIONS IN PROGRAMS 31
8. Introduction to Shell programs
The UNIX shell is a command language interpreter. A shell Program is an ASCII file, containing a series of UNIX commands that are to be executed.
There are several different versions of UNIX shells in existence, the main types being the ‘Bourne', ‘Korn', POSIX and ‘C' shells. The default shell used by most system utilities is the ‘Bourne' shell and this forms the basis of this module, with additional ‘Korn' shell variants.
A shell program may simply contain a list of standard UNIX commands to be carried out, or it may be more complex, including program structures such as ‘if' statements, ‘while' loops etc.
# dirclear.shl written 12/2/98
find . –atime +60 –exec rm –i {} ;
An example 1 line program to search the current directory for files last accessed more than 50 days ago, and offer them for deletion.
Note the hash sign ‘#' is used to signify a comment. Anything following the hash is not normally acted on by the shell.
8.1 Executing Shell programs
When a file is created, containing a shell program, it will be given whatever default file permissions have been set up on the system. In order to run a shell program by simply typing in the file name at the command prompt, the file must first be made ‘executable' using the ‘chmod' command. For example:
chmod u+x dirclear.shl
would make the file executable and then it could be run by entering the filename at the command prompt.
8.2 Alternative methods of execution
There are other methods of executing shell programs as shown below.
sh filename allows program to be run without execute permission being set provided you are the owner of the file.
sh –x filename as above, but also switches on a ‘trace' function so that the lines of the program are displayed prior to being executed. Normally used for debugging new programs.
exec filename runs program without opening a sub shell. When program is terminated it will not be able to return to original shell.
. filename runs program in shared memory space with existing shell, allowing passing of parameters between both programs.
8.3 Location of Shell programs
Once shell programs have been created and made executable, they can be utilised in exactly the same way as other existing UNIX commands.
It is normal practice to store command files in a ‘bin' type directory that is searched for by the system ‘PATH' variable. If the commands are for local use only, a ‘bin' directory could be created beneath the users ‘HOME' directory. If new commands are to be made available globally across the system, the files would be placed in, for example, the ‘/usr/local/bin' directory.
8.4 Variables in Shell programs
There are several different methods of assigning values to variables within UNIX, either at the command prompt or within shell programs
8.4.1 Direct Assignment
One of the most common methods of assigning a value to a variable is by direct assignment, using the following format.
var=value
where ‘var' is an arbitrary variable name and ‘value' is the integer or string value being assigned to it. Note that variable names may be in upper case or lower case characters.
num=10 assigns the value ‘10' to a variable ‘num'
DIR=/user0/jayr/prog assigns the string /user0/jayr/prog to the variable ‘DIR'
This method is used extensively in setting up variables in system and user environments by inclusion in ‘profile' files.
8.4.2 Exporting variables
Once a variable has been assigned within an environment, by whatever means, it is available for use by and recognised within, the current shell. If it is required to use the variable in subsequent ‘sub shells' and sub-processes , it must first be tagged as ‘exported'. This is done with the ‘export' command, using the following format.
export variable_name(s)
DIR1=/usr/jayr
LIST="jayr anna ness jo"
export DIR1 LIST
Again, this method is very common within ‘profile' files on UNIX systems, in order to set up and export variables that a user will need during logon and subsequent processes.
Note: If it is required to define a variable ‘globally' so that it can be used by all users, it could be set up in /etc/profile, as this file is read by all users as they log on to the system.
8.4.3 Assigning variables with read
A value can be assigned to a variable, during the running of a program, by use of the ‘read' command.
read variable_name
The read command causes the program to wait for something to be typed in on the keyboard. Whatever is typed in is then assigned as the value of ‘variable_name'
echo “Enter Terminal Type :c"
read TERM
export TERM
A message is printed on the screen, requesting the user to enter the terminal type. The read command waits for input from the keyboard and when something is entered, assigns this value to the variable ‘TERM'. The value of ‘TERM' is then exported for use in subsequent sub shells. Note: The ‘c' at the end of the line cancels the default ‘new line', thus keeping the screen cursor at the end of the line until the key is entered.
8.4.4 Command Substitution
The output of a command line, after it has been executed can also be written to a variable, using the following format.
var=`command` or var=$(command)(Ksh or POSIX)
where ‘command' will be executed first, and it's resulting ouput then written in to the variable. Note the use of ‘grave accents' around `command`. On a vt220 type keyboard these are the ` above the ‘TAB' key. The ‘$' sign and brackets have the same effect..
LIST=`who|cut –c0-8` or LIST=$(who|cut –c0-8)
Variable LIST would contain a list of logged on users names.
8.4.5 Variable Expansion
When it is required for the shell to use the value contained within a variable, the variable name is presented to the shell, preceded by a dollar sign ($) [or the equivalent on your keyboard].
TERM=vt220
export TERM
echo $TERM
vt220
When the ‘echo' command is executed, the ‘$' sign is recognised by the shell. The value of TERM (vt220) is substituted and used as the argument for the ‘echo' command.
8.4.6 Variable Evaluation
The contents of a named variable can be evaluated and an action carried out dependent upon the results of that evaluation. Some of the formats used are as follows:
command ${variable:-word}
If ‘variable' is set and is not null, use its value. If not use ‘word'.
write ${LIST:-ctatrnr}
If ‘LIST' has a value, ( e.g. a list of user id's ), write to them. If not write to ‘ctatrnr'.
command ${variable:+word}
If ‘variable' is set and is not null, use word. If not use nothing.
write ${LIST:+jayr} 2>/dev/null
If ‘LIST' has a value, ‘write' to jayr. If not, write to nothing. Note error redirection to get rid of error message if executing ‘write' without a destination user name.
Note: There are many other types of variable evaluation. Reference should be made to the ‘man' pages under ‘sh' or ‘ksh' for other variations.
8.4.7 Positional Variables
The shell places all words that are entered on the command line into pre-set variables, determined by the position of the word on the command line. The command itself that invokes a shell is placed into a variable called $0, the first argument into variable $1, the second into $2 and so on, up to a limit of $9.
This facility is often used to introduce variables into a shell program, rather than using the ‘read' command.
Consider the following ‘search' program, which could be used to search a specified directory structure for a particular file. It could be written in two different ways.
#search1 program
echo “Enter file name to search for :c"
read ANS
echo “Enter start Directory to search from:c"
read DIR
find $DIR –name $ANS -print
Program is executed by entering ‘search1' command. User is then prompted to enter filename and start directory for search. An alternative method of coding, using positional variables would be as follows:
#search2 program
find $1 –name $2 –print
A much shorter program to achieve the same effect. However, it relies on the user knowing the correct syntax to execute the program with.
search2 dir_name file_name
Note that it may be necessary to put quotes around variables when used in programs, in case the data contains any special characters.
8.4.8 System Variables
The following are some examples of system variables that are automatically set by the shell.
$# Total number of positional variables entered
$* All positional variables
$? The exit value of the last command entered
$$ The process id number of the current shell
$! The process id number of the last background command
The following are some examples of common variables used by the Korn/Bourne/POSIX shells. They are often customised to specific values in users environments.
HOME Users' default directory
PATH Directory search path for commands
MAIL Location of users' mail file
LOGNAME Users' login id name
PS1 Primary command line prompt. Default ‘$'
PS2 Secondary prompt. Default ‘>'
IFS Internal field separators.(normally space, tab, newline)
TERM Terminal type being used. Required for utilities like editors.
8.4.9 Viewing variables
The ‘env' command, executed on its own, will display all variables that exist in the current environment, along with their current value.
env|more
LOGNAME=ctatrnr
MAIL=/var/mail/ctatrnr
GLOBAL_HOME=/cabs/ctao57/gbl/cta571_003
LOCAL_HOME=/cabs/ctao57/run/ctatrnr/o57
HOSTNAME=dopey
8.5 Control Structures in Shell Programs
Control structures, such as ‘if statements' and ‘while loops' used in shell programs are similar in construction to those used in other programming languages, with some variations unique to UNIX.
8.5.1 Conditional statements with if
This construction allows alternative commands to be performed, depending upon stipulated conditions being met. The basic syntax used with ‘if' is as follows:
if this statement is true
then
run these commands
else
run these commands
fi
The following example program, called ‘send', checks to see if a nominated user is currently logged on. (i.e. the ‘grep' is successful), the ‘memo' file is sent using ‘write'. If they are not logged on, the file is sent using ‘mail' and the originator informed.
# ‘send program'
echo “enter user name to send memo to :c"
read NAME
if who|grep “$NAME" > /dev/null
then
write “$NAME" < memo
else
mail “$NAME" < memo
echo “ $NAME not logged on-memo sent by mail"
fi
8.5.2 Using if with test statements
As well as testing against commands for success or failure, the if command can also be used to test entities against predefined criteria. The three types of entity that can be tested are strings, integers and file operators.
(a) Strings
(b)
Operator Result true when:
string1 = string2 string1 identical to string2
string1 != string2 string1 not identical to string2
string string is NOT null
-z string string is zero in length
The following example program shows a typical use of a ‘test' against a string operator. The square brackets cause the shell to invoke the ‘test' command. The program checks the users' log on name, stored in the variable ‘LOGNAME' and if it is not ‘root' carries out the commands directly after the ‘then' statement. The ‘exit' command breaks out of the program, if the test failed.
# checkuser program
if [ `id|cut –c5` != “0" ]
then
echo “ You do not have authority ! “
exit
else
menuprog
fi
(c) Integers
Operators Result true when:
int1 –eq int2 int1 is equal to int2
int1 –ge int2 int1 is greater than or equal to int2
int1 –gt int2 int1 is greater than int2
int1 –le int2 int1 is less than or equal to int2
int1 –ne int2 int1 is not equal to int2
In the following example program, called ‘show', the file name that is input at the command line undergoes a line count. This is then piped to the ‘cut' command, which extracts just the number of lines. If the number of lines is less than 20 the file is displayed using ‘cat'. If there are more than 20 lines, the file is displayed using ‘pg'.
# show program – execute with ‘show file_name'
if [ ‘wc –l $1|cut –c0-8` –lt 20 ]
then
cat $1
else
pg –p “Return to continue or ‘h' for help" $1
fi
(d) File Operators
The following are the most common file operators. For additional variations, consult the ‘man' pages on the system.
Operator Result true when:
-d file_name file_name is a directory
-f file_name file_name exists and is an ordinary file
-r file_name file_name is readable by the process
-s file_name file_name is non zero in length
-w file_name file_name is writeable by the process
-x file_name file_name is executable by the process
The following example program checks to see if the file ‘CUSTOM.ksh exists in the directory given by $HOME. If it does, it is then executed. If not an error message is given.
# Common CTA environment setup
if [ -f $HOME/CUSTOM.ksh ]
then
echo "Executing Common CTA environment setup"
. $HOME/CUSTOM.ksh >/dev/null
else
echo "
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
echo "Link for CUSTOM.ksh not defined - Environment not set up correctly"
fi
8.5.3 Testing conditions with && and ||
The ‘&&' and ‘||' constructs perform a function similar to an ‘if' statement. They allow a command in a program to be executed, or not, dependent on the success or failure of a preceding command. The basic syntax is as follows.
command1 && command2
Where command2 is only executed if command1 is successful, that is, returns a ‘0' exit status.
grep “jayr" /etc/passwd >/dev/null && echo “Exists"
If the user ‘jayr' exists in /etc/passwd then the message ‘Exists' will be displayed. If ‘jayr' does not exist, the ‘echo' command will not be run.
command1 || command2
Where command2 is only executed if command1 fails, that is, has a ‘non-0'' exit status.
grep “jayr" /etc/passwd || echo “ Does not exist"
Where if the user name 'jayr' is NOT found, the message, “ Does not exist", WILL be printed.
These types of constructions are also often seen used with ‘if' statements as in the following example.
if [`id|cut –c5` = “0" ] && [ ‘tty' !=/dev/console]
then
echo “Logon to root only allowed at console “
exit 1
else
continue
fi
8.6 Pattern Matching with case statements
As an alternative to using multiple ‘if' statements to check a set of varying conditions, they can be checked by using the ‘case' statement. This compares a value (normally held in a variable) against a series of possible patterns and executes a set of commands if a match for the pattern is found. The standard syntax is as follows:
case value in
pattern1) command_list ;;
pattern2) command_list ;;
pattern3) command_list ;;
esac
The content of ‘value' is checked successively against patterns 1, 2 and 3. If a match is found, the appropriate list of commands is executed up until the double semi-colon. The shell then moves from there to the end of the statement, which is recognised by the ‘esac' statement.
A common use of ‘case' statements is in menu programs, an example of which is shown below:
#menu program
echo “ OPS MENU Display File List 1 Search for file 2 Display File Type 3 Exit from Menu 4 Enter Option :c" read OPT case $OPT in 1) ls –al ;; 2) echo “Enter filename :c" read ANS find / -name $ANS –print 2> /dev/null ;; 3) echo “ Enter Filename :c" read ANS file $ANS ;; 4) exit ;; *) echo “ You MUST Enter option 1-4 “ exit ;; esac
Note the use of the shell wild card ‘*' as a ‘catch all' pattern at the end of the program. All of the shell wild cards can be used in pattern matching. Also a logical ‘or' can be performed in pattern matching by inserting a ‘|' sign between two patterns, as in the following example.
Y|y) command_list ;;
Would mean that the command list would be executed if the value being checked for in the ‘case' statement was either ‘Y' OR ‘y' .
8.7 Repeated executions with for loops
The ‘for' command can be used to execute a command list repeatedly, a specified number of times.
for variable in word1 word2 word3……..wordn do command_list done
The ‘command_list' will be executed the same number of times as the number of ‘words' after the ‘in'. The contents of ‘word1' are assigned to ‘variable' the first time through the loop, the contents of ‘word2' are assigned the second time through the loop and so on. The loop terminates after using ‘wordn'.
#write check program
list=`who|cut –c0-8|grep –v “^ops.*" ` for NAME in $list do write $NAME < memo_file echo “Message sent to $NAME" done
The program will find out who is logged on, discard any user names beginning with ‘ops' and then ‘write' to each in turn sending the contents of ‘memo_file'. A screen message will be displayed as each message is sent. The loop terminates after using the last name in ‘list'.
8.8 Repeated Executions with while loops
The while command provides the facility to execute a list of commands, in a loop, dependent upon whether an initial statement remains true or not. The basic syntax is as follows:
while this_command_is_true do command list done
The command after the ‘while' is executed. If it is true, the loop is entered and command list is run. On reaching the ‘done', the loop goes back to the beginning. If the command after the ‘while' is still true , the loop will be repeated again. The loop will finally stop when the command after the ‘while' becomes false.
#time loop program num=10 while [ $num –gt 0 ] do banner $num sleep 1 num=`expr $num – 1 ` done
8.8.1 Continuous loops with while true
Continuous loops can be executed by putting the word ‘true' as the statement after the ‘while' command. This will make the loop run until it is broken by an ‘interrupt' or some other form of exit.
# inhibit logons program while true do SPAM=`whoami |cut –c0-7` OTHER=`who –u|grep –v $SPAM|cut –c45-50` kill –9 $OTHER sleep 10 done
8.8.2 Breaking from loops
As seen earlier, the ‘exit' command can be used to leave a loop. However, this exits totally from the program. It is possible to escape from a loop and continue in the same program. This is done by using either the ‘break' or the ‘continue' commands.
The break command will cause an exit from the loop, continuing with the next command that follows the ‘done' statement.
# checkuser tput clear echo “ Enter terminal to check :c" read ANS num=0 while true do num=`expr $num +1` if [ $num –ge 10 ] then break else ps –l –t $ANS sleep 1 tput clear fi done logoff.prog
If ‘continue' is used, the program will skip the rest of the loop, go directly to the ‘done' and then restart the loop again.
#display.check program
for file in $file_list do if [ !-f $file ] then echo “File $file does not exist" continue fi cat $file done
8.9 Overview of the awk utility
‘awk' is a complete and extensive data formatting language, with many of its constructions being similar to those used in the ‘C' programming language. In this module, only the basic functions are covered and further information can be obtained from the ‘man' pages and any of the many books that deal exclusively with ‘awk' programming. ‘awk' has a syntax that is similar to that of ‘sed''. However, the pattern constructions and actions are different.
awk ‘ /pattern/ { action } ‘ file_name
If ‘pattern' is omitted, a match of every line is assumed and the ‘action' is performed on every line.
awk ‘ { print } ‘ /etc/group
Would print every line from the file /etc/group (Not very effective!)
awk ‘ /bin/ { print } ‘ /etc/group
Would print only lines containing ‘bin' from the file /etc/group
8.9.1 Fields in awk
When a line is read in by awk, it writes each individual word ( split , by default, on white space ) into a numbered buffer in memory. These buffers are numbered $0, $1, $2, $3…..$n. $0 contains the whole line and the other buffers hold one word each, starting from the left hand side.
For example, if the line “ Good morning its 2 am" was read in by awk, it would be broken down as follows:
Buffer no. Content
$0 Good morning its 2 am
$1 Good
$2 morning
$3 its
$4 2
$5 am
8.9.2 Relational expressions with awk
Awk recognises the characters ‘ ^ $ . [] * ‘ as previously used with ‘sed' and ‘grep', while also supporting the following relational characters.
Operator Action
< Less than
<= Less than or equal to
== Equal
!= Not equal to
>= Greater than or equal to
> Equal to
~ Matches
!~ Does not match
$3>100 select lines where 3rd field is bigger than 100
$1>="S" select lines where 1st field contains letters S through Z
$1==$5 select lines where 1st field is equal to 5th field
$4~/UNIX System/ { print $1 } select lines where 4th field matches the pattern ‘UNIX System' and print out 1st field
$4!~/UNIX System/ { print $1 } print out 1st field, only if 4th field does NOT match ‘UNIX System'
8.9.3 Built in awk variables
There are several standard variables that are recognised by awk. Some of the more common variants are shown below:
Variable name Value held
NR Input record number since beginning
NF Number of fields in current record
FS Input field separator ( default blank )
OFS Output field separator ( default blank )
ORS Output record separator ( default new line)
RS Input record separator ( default new line )
The following example would extract from the file /etc/passwd any line where field 1 is ‘ctatrnr' and then print only field 5.
awk ‘{ FS=":" } $1~/ctatrnr/ { print $5 }' /etc/passwd
Training Account Administrator
The following example would extract from the file /etc/passwd any user id less than, or equal to 100, prints the user id name ( field 1), inserts the text string ““has an id of"" and the prints the user id number (field 3 ).
awk ‘ { FS=":" } $3<=100 { print $1, “has an id of:", $3 } ‘ /etc/passwd
root has an id of: 0
daemon has an id of: 1
bin has an id of: 2
sys has an id of: 3
adm has an id of: 4
8.9.4 Using awk scripts
As well as being used directly from the command line, awk statements can also be written into a file which is subsequently invoked by the awk command. The basic syntax is as follows:
awk –f awk_file file_name
Where ‘awk_file' is the name of the script containing the ‘awk' statements to be performed, when reading in the contents of ‘file_name'.
‘awk' has two special keywords, BEGIN and END, which are executed before the first record and after the last record. They are often used to provide header and footer functions to reports formulated with ‘awk'. An example ‘awk' script file is shown below:
BEGIN { FS=":"
OFS=" "
print “ LIST OF SYSTEM USER ID'S “
print “-------------------------------------------“
}
$3<=100 { print $1," “,$3," “,$6 }
END { print “
"
print “--------------End of List -----------------“
}
If this file was saved under the name ‘idlist', it could then be invoked at any time in the future by executing the ‘awk' command as follows:
awk –f idlist /etc/passwd
where the ‘-f' is followed by the name of the file containing the ‘awk' statements to be used.
The resultant ouput of the command would be as follows.
ctatrnr@dopey> awk -f idlist /etc/passwd
LIST OF SYSTEM USER ID'S
-------------------------------------------------------------
root 0 /
daemon 1 /
bin 2 /usr/bin
sys 3 /
adm 4 /var/adm
uucp 5 /var/spool/uucppublic
lp 9 /var/spool/lp
hpdb 27 /
sysadm 0 /home/sysadm
jetform 40 /home/jetform
--------------------------------END OF LIST-----------------------------
There are many more things that can be done with the ‘awk' command. Complete programs can be written within the ‘action' brackets, performing complex manipulation of data. For further details, reference should be made to the UNIX ‘man' pages.
8.10 Signal Handling with trap
All UNIX processes that are running have a signal table, in memory that defines how they react to receiving any of the signals that are seen with the ‘kill –l ‘ command. On receiving a signal, each process can take one of three types of action. These are (a) Ignore the signal, (b) Take a default action, set up by the operating system, (c) Run some other routine that the process is directed to.
What action a shell takes on receipt of a signal can be controlled in shell programs by use of the ‘trap' command.
(a) Signals can be ‘trapped' to ignore signals by placing a ‘null string' as the first argument to the ‘trap' command, as shown below:
trap “" 2 3 15
This would cause the current shell program to ignore the receipt of signals 2,3 and 15. This is often used to prevent users from breaking out of a program and returning to the command line.
(b) In the absence of any signal ‘traps', a process will take the default action on receipt of a signal.
(b) A process is directed to some other routine, on receipt of a signal, by including the relevant command(s) within the quotes after the ‘trap' command.
trap “rm jaytemp" 0 2 3 15
This would cause the file ‘jaytemp' to be removed if any of the listed signals are received by the current program. Note, ‘signal 0' is produced at end of the program.
trap 2
Using trap without any action before the signal list, restores the listed signal(s) to their default action for the remainder of the program, or until they are subsequently ‘re-trapped'.
Note: It is not possible to trap out the action of the ‘signal 9' ( KILL )
8.11 Replacing commands with alias or function commands
To avoid repeated coding or to produce new versions of commands, use can be made of ‘functions' and/or ‘aliases' (alias not available in Bourne shell).
8.11.1 Using alias in programs
The ‘alias' command, entered on its own will produce a list of previously defined aliases and their current equivalents.
ctatrnr>alias
cls=clear
del=rm -i
dir=ls -al
Aliases can be defined ( in the Korn shell ) at any time and are often defined in ‘profile' files to provide shortcuts for commonly used commands. The ‘-x' option used below exports the meaning of the ‘alias' across subsequent shells.
alias –x del="rm –i" Creates a command ‘del' that performs the same function a ‘rm –i'
alias –x proc="ps –ef|pg" Creates a command called 'proc' that produces a ‘paged' process listing.
alias proc Would show any equivalent that is currently set for the alias ‘proc'.
unalias proc Would remove the alias that is currently set for ‘proc'.
8.11.2 Using functions in programs
‘Functions' are commonly used in shell programs to replace repetitively coded routines. The basic syntax is as follows.
function_name()
{
command(s)
}
The example below defines a function called ‘conscheck', which checks to see if the user is currently logged on at the system console.
conscheck()
{
if [ ‘tty' != “/dev/console" ]
then
echo “Must be on console to run this program"
exit 0
fi
}
Once the above function has been defined, the word ‘conscheck' could be used whenever this routine needs to be run.
|
|