Ksh Reference
Transcript of Ksh Reference
Korn Shell Syntax - A Reference Guide
Korn Shell SyntaxA Reference Guide
provided by:Context-Switch Limited
Context-Switch LimitedEgham, Surrey, UK
http://www.context-switch.com
Korn Shell Syntax - A Reference Guide
Korn Shell Syntax Reference
The following details provide a reference of the syntax available within the Korn shell. Not all
syntax is covered in these pages. Please refer to the man pages for the Korn shell or equivalent
(for example, the POSIX shell in the HP-UX™ environment) for additional information.
Filename and Directory-name Substitution:
The Korn shell has a number of metacharacters and pattern-structures that can be used to
substitute filenames and directory names on a command line. These are quite often referred to
as wildcard characters.
The shell will substitute, on the command line, any file or directory name that matches the
pattern supplied on the command line.
Table 1: Shell Meta Characters
Shell Meta Character Description
? Match any single character.
* Match zero, 1 or more characters.
[...] A character class. This can be used in the following ways:
[abc] Match any single, specified, character.
[a-zA-Z0-9] Match any of the ranges of characters (Alphabetic/Numeric).
Note: ranges must be valid
[!...] Negate - Do not match any character specified within the
character class.
?(pat1|...|patn) Match zero or 1 of the specified patterns.
@(pat1|...|patn) Match exactly 1 of the specified patterns.
*(pat1|...|patn) Match exactly 1 of the specified patterns.
+(pat1|...|patn) Match zero, 1 or more of the specified patterns.
!(pat1|...|patn) Match any pattern except the patterns specified.
Korn Shell Syntax - A Reference Guide
String Variable Assignment:
In the Korn shell, string variables must be assigned values using the syntax:
variable_name=value
If a variable is to used as an ENVIRONMENT variable, is must be marked for export to sub-
processes using the export command.
variable_name=value export variable_name
* NOTE: When variables are assigned Left or Right-alignment formatting, using the typesetcommand, the typeset display output characteristics will only be applied if the variable isquoted within double-quotes (“) on the shell command line. (See Variable Substitution)
Table 2: String Variable Assignment
Syntax Meaning
var=value Assign value as the contents of the variable var.
var="v1 v2 v3" Assign the three words v1 v2 v3 as the contents of
the variable var.
var=$var2 Assign the contents of variable var2 to the variable
var.
var=$(cmd) Assign the output of the UNIX command, cmd, as the
contents of the variable var.
var=`cmd` Bourne shell equivalent of the above command output
assignment (supported within the Korn shell).
var= Assign NULL as the contents of the variable var.
var[n]=value Assign value as the contents of the nth element of
array variable var.
typeset -l var=Val Assign the value, val, to the variable, var, and force
the contents to be displayed/substituted as lower-case
(eg: val).
typeset -u var=Val Assign the value, val, to the variable, var, and force
the contents to be displayed/substituted as upper-case
(eg: VAL).
typeset -L20 var=val Assign the value, val, to the variable, var, and set
display attributes to be left-aligned, truncated to 20
characters.*
typeset -RZ20 var=val Assign the value, val, to the variable, var, and set
display attributes to be right-aligned, truncated to 20
characters.*
Korn Shell Syntax - A Reference Guide
Integer Variable Assignment:
The Korn shell supports integer variables and provides a range of integer artihmetic fucntions.
These are described below:
Table 3: Integer Variable Assignment
Syntax Meaning
typeset -i var=n Assign the integer number, n, to the integer (numeric)
variable var.
integer var=n The word, integer, is an alias for typeset -i. This
assignment is, therefore, the same as shown above.
(( var = $var + n )) Add the integer value, n, to the current contents of the
numeric variable, var, and store result in variable
var.
((var+=n)) Same as above.
(( var = $var - n )) Subtract the integer value, n, from the current contents
of the numeric variable, var, and store result in
variable var.
((var-=n)) Same as above.
(( var = $var * n )) Multiple the current contents of the numeric variable,
var, by the integer value, n, and store result in
variable var.
((var*=n)) Same as above.
(( var = $var / n ) Divide the current contents of the numeric variable,
var, by the integer value, n, and store result in
variable var.
((var/=n)) Same as above.
(( var = $var % n )) Divide the current contents of the numeric variable,
var, by the integer value, n, and store the integer
remainder in variable var.
((var%=n)) Same as above.
typeset -LZ20 var=val Assign the value, val, to the variable, var, and fix the
maximum length of the variable contents to 20
characters, left-aligned, with leading zeros stripped.
typeset -RZ20 var=val Assign the value, val, to the variable, var, and fix the
maximum length of the variable contents to 20
characters, right-aligned, with leading zeros inserted.
Korn Shell Syntax - A Reference Guide
Variable Substitution:
The Korn shell has a number of metacharacters and pattern-structures which can be used to
substitute the contents of variables on a command line. These are described below.
The dollar character ($) must precede the variable name to force the shell to perform a
substitution.
Table 4: Command-lineVariable Substitution
Syntax Meaning
$var Substitute with the contents of the variable var.
${var}text Substitute with the contents of the variable var and
append the characters, text, to the substituted
contents.
${#var} Substitute with the number of characters stored in the
variable var. If the content is NULL, the substitution
value would be 0 (zero)
${var:-alt} If the variable has NULL contents, substitute with the
alternative value, alt. The current variable contents
are retained in the variable store.
${var:+alt} If the variable has NOT NULL contents, substitute
with the alternative value, alt. The current variable
contents are retained in the variable store.
${var:=alt} If the variable has NOT NULL contents, substitute
with the alternative value, alt. The alternative value
would, then, be retained as the contents of the
variable, var
${var:?err} If the variable has NULL contents, do not perform a
substitution but display the error message, err, and
exit from that shell with an error status.
${var[n]} Substitute with all elements of the array variable, var.
${var[*]} Substitute with all elements of the array variable, var.
${#var[*]} Substitute with the current number of (used) elements
in the array variable, var.
The maximum allowed number of elements is 4096
but may vary depending upon vendor
implementation.
Korn Shell Syntax - A Reference Guide
If the literal contents of the variable are to be substituted, the variables substitution controls
must be enclosed in double-quotes ("). Also, variables that have been left- or right-aligned,
using the typeset command, must be enclosed within double-quotes for their formatting to
be applicable at the time of substitution.
For example, if the literal contents of variable, myvar, consist of the following two lines of
text:
This is line 1This is line 2
The output of quoted and unquoted variable substitions would be as shown below:
$ echo $myvarThis is line 1 This is line 2
$ echo "$myvar"This is line 1This is line 2
Special Shell variables
A number of shell-maintained variables are available within the Korn shell. These variables are
regularly updated by the shell, as comman lines are executed, directories are changed and such
like. These variables include:
It is common practice to use the $$ (current PID value) as an extension to named files. For
example:
echo "Current PID value is $$" >> /tmp/logfile.$$
Table 5: Shell-maintained Variables
Syntax Meaning
$$ Substitute with the current processID value.
$? Substitute with the return-status value of the
preceding command line.
$! Substitute with the processID of the most-recent
background process.
$* Substitute with the list of arguments in the current
shell parameter list.A parameter list can be generated
using the set command.
$@ Same as above except that the list is the lst of actual
arguments rather than a list of argument words.
$# Substitute with the number of arguments in the
current shell parameter list.
Korn Shell Syntax - A Reference Guide
Command Substitution:
In the Korn shell, it is possible to substitute the output of a command within a command line,
in a similar manner to using variable or filename substitution.
The Korn shell supports the older, Bourne, shell form of syntax but also has its own specific
form of syntax for command substitution.
Bourne shell syntax for command substitution uses the command quotes (back quotes):
$ command `command_to_substitute`
The command_to_substitute would be run first and its output would be substituted onto the
command line, to be used by command. For example:
$ echo `date`
would echo the current date and time details (which were output by the date command).
The Korn shell alternative to the command quotes is: $(...) where ... represents the command
being run. An example is shown below.
$ command $(command_to_substitute)
The two commands, listed below, are identical in terms of their interpretation by the Korn shell:
$ echo `date`$ echo $(date)
Variables can also be assigned the output of a command. An example is provided below:
$ var=$(date)
In the example above, the variable var will contain the output of the date command. Although
the output of the date command consists of many words, it is not required to quote to
command substitution text.
Korn Shell Syntax - A Reference Guide
Redirection - Summary:
The three data-flow channels which exist, as standard, in all shells are called standard input,
standard output and standard error output. These are more commonly know as stdin, stdout and
stderr, respectively.
Each data-flow channel has a file descriptor number. These are 0, 1 and 2 for stdin, stdout and
stderr, respectively. The redirection control can be preceded by the file descriptor number to
define which data-flow channel is to be redirected.
By default, the shell attaches these data-flow channels to the current device file (associated withyour terminal). A redirection control, therefore, is merely instructing the shell to associate the
data-flow channel with an alternative filename. The rule, therefore, is always to follow a
redirection control with a file pathname.
Here are some examples of redirection syntax:
1. Redirect stdin from the named file on the command line:
$ command < file_name
2. Redirect stdout to the named file (file_name) on the command line:
$ command > file_name
The shell saves the output of command in file_name. It creates file_name if it does not exist.
Otherwise, it overwrites (replaces/clobbers) the current contents of the file.
3. Append stdout, to a named file, on the command line:
$ command >> file_name
This creates file_name if it does not exist. Otherwise, the output from command is appended to
the end of file_name.
4. Redirect stderr to the named file, on the command line:
$ command 2> file_name
5. Append stderr to the named file, file_name, on the command line:
$ command 2>> file_name
Shell Pipelines
Data output can be transferred to become another command’s input. This is managed by the
shell using a facility know as a pipeline. To create a pipeline, each command is separated by the
pipe (vertical-bar) character.
Command lines that employ this facility are referred to as a pipeline commands (or pipes):
$ command1 | command2 | command3 | ... | commandn
A command preceding a pipe character must write its output on stdout.A command that follows a pipe character must accept input on stdin.
Korn Shell Syntax - A Reference Guide
More on Redirection - Summary:
Redirect stdout to the NULL device. This is common practice within shell scripts to dispense
with any output which would, otherwise, be displayed on the screen.
$ command > /dev/null
Redirect stderr to the NULL device. This is common practice within shell scripts to dispense
with any error output which would, otherwise, be displayed on the screen.
$ command 2> /dev/null
To prevent the possible overwriting (clobbering) of an existing file's data, you can turn on the
Korn shell's noclobber attribute.
$ set -o noclobber
If noclobber is set, you can override it using the following syntax. The first example shows the
use of the override feature with stdout. The second example shows the use of the override
feature with stderr. The character which follows the > symbol is the pipe (|) character.
$ command >| /dev/null$ command 2>| /dev/null
To turn off the noclobber attribute, you should give the command:
$ set +o noclobber
Additional File Descriptor Redirection - Summary:
The Korn shell has a range of file descriptors in addition to stdin, stdout and stderr. These file
descriptors have the numeric values 3 through to 9.
Each file descriptor may be associated with a file. Once that file is opened, all output which is
redirected using that file descriptor number will be appended to the associated file. All input,
using that file descriptor number, will be read in from the associated file.
To open a filename associated with a file descriptor, use one of the following commands:
exec fd_num< file_pathname #(open for input)exec fd_num> file_pathname #(open for output)exec fd_num< file_pathname #(open for input and output)
Where fd_num would be a number between 3 and 9 and file_pathname would be the
name of the file to be associated with that file-descriptor.
To close a filename associated with a file descriptor, use one of the following commands:
exec fd_num<&- #(closes input file)exec fd_num>&- #(closes output file)
For example:
exec 3> store_file #(open file for output)ls -l >&3 #(store output)date >&3 #(store output)exec 3>&- #(close file)
Korn Shell Syntax - A Reference Guide
Conditional Expressions:
A conditional expression would be used to test attributes of files and to compare strings. The
test command can be used to test the result of the conditional expression.
The test command has a number of forms:
1. The form: test <condition>
2. The form: [ <condition> ] 1
3. The form: [[ <condition> ]] 2
A conditional expression is used with the [[ compound command to test attributes of files and
to compare strings. Word splitting and filename generation are not performed on the words
between [[ and ]]. See "The Test Statement" for details of [[.
Each expression can be constructed from one or more of the following unary or binary
expressions:
1. Because the single [ and double [[ are alternatives to a command word, they must be followed by a
minimum of one whitspace character.
2. Similarly, the closing ] or ]] must be preceded by a minimum of one whitespace character.
Table 6: Conditional Expressions
Condition Description
-a file True if file exists
-b file True if file exists and is a block special file.
-c file True if file exists and is a character special file.
-d file True if file exists and is a directory.
-f file True if file exists and is an ordinary file.
-g file True if file exists and is has its setgid bit set.
-h file True if file exists and is a symbolic link.
-k file True if file exists and is has its sticky bit set.
-n string True if length of string is non-zero.
-o option True if option named option is on.
-p file True if file exists and is a fifo special file or a pipe.
-r file True if file exists and is readable by current process.
-s file True if file exists and has size greater than zero.
-t file_descriptor True if file descriptor number file_descriptoris open and associated with a terminal device.
-u file True if file exists and is has its setuid bit set.
Korn Shell Syntax - A Reference Guide
-w file True if file exists and is writable by current process.
-x file True if file exists and is executable by current process.
Alternatively, true if file exists and is a directory, the
current process has permission to search in the
directory.
-z string True if length of string is zero.
-H file True if file exists and is a hidden directory.
-L file True if file exists and is a symbolic link
-O file True if file exists and is owned by the effective user ID
of the current process
-G file True if file exists and its group matches the effective
group ID of this process.
-S file True if file exists and is a socket.
file1 -nt file2 True if file1 exists and is newer than file2
file1 -ot file2 True if file1 exists and is older than file2
file1 -ef file2 True if file1 and file2 both exist and refer to the
same file.
str = pattern True if string, str, matches the pattern. The pattern
can be a literal string or consist of shell filename
substitution meta-characters or combination.
str != pattern True if string, str, does not match pattern
str1 < str2 True if str1 comes before str2 based on the
ASCII value of their characters
str1 > str2 True if str1 comes after str2 based on the
ASCII value of their characters
str < pattern True if str1 comes before str2 based on the
ASCII value of their characters
exp1 -eq exp2 True if exp1 is equal to exp2.
exp1 -ne exp2 True if exp1 is not equal to exp2.
exp1 -lt exp2 True if exp1 is less than exp2.
exp1 -gt exp2 True if exp1 is greater than exp2.
exp1 -le exp2 True if exp1 is less than or equal to exp2.
exp1 -ge exp2 True if exp1 is greater thanor equal to exp2.
Table 6: Conditional Expressions
Condition Description
Korn Shell Syntax - A Reference Guide
Compound Expressions
A compound expression can be constructed from these primitives by using any of the following,
listed in decreasing order of precedence.
Table 7: Compound Expressions
Compound Expression Description
(expression) True, if expression is true. The round-brackets are used to
group expressions.
! expression True if expression is false.
! is syntax used by the shell to represent NOT.
expr1 && expr2 True, if both expr1 and expr2 are true.
&& is the syntax for Logical-ANDNote: This is Korn shell specific syntax. When used with the testcondition, is only applicable with the command words test or[[ ... ]]
(See Bourne shell compatible syntax, below)
expr1 || expr2 True, if either expr1 or expr2 is true.
|| is the syntax for Logical-ORNote: This is Korn shell specific syntax. When used with the testcondition, is only applicable with the command words test or[[ ... ]]
(See Bourne shell compatible syntax, below)
expr1 -a expr2 Bourne shell compatibleTrue, if both expr1 and expr2 are true.
Note: This is Bourne shell syntax. When used with the testcondition, is only applicable with the command words test or[ ... ]
expr1 -o expr2 Bourne shell compatibleTrue, if either expr1 or expr2 is true.
|| is the syntax for Logical-ORNote: This is Bourne shell syntax. When used with the testcondition, is only applicable with the command words test or[ ... ]
Korn Shell Syntax - A Reference Guide
The Test Statement:
The test statement can take any of the following forms:
Note that the characters, [ and [[ , represents to command word test and must be followed
by at least one white-space character. The closing square bracket(s) must be preceded by at least
one white-space character.
The AND and OR statements differ between the Bourne and the Korn shell syntax.
Korn shell syntax:[[ condition1 && condition2 ]] # (condition 1 AND condition 2)
[[ condition1 || condition2 ]] # (condition 1 AND condition 2)
Bourne shell syntax:[ condition1 -a condition2 ] # (condition 1 AND condition 2)
[ condition1 -o condition2 ] # (condition 1 OR condition 2)
The -a and -o clauses can not be used inside the Korn shell-specific, [[ ... ]], teststatement.
Table 8:
Test statement syntax Description
test cmd1 Test for the successful execution (byevaluating the return status) of the
command, cmd1.
[[ cmd1 ]] Test for the successful execution (byevaluating the return status) of the
command, cmd1.
Korn shell specific syntax
[ cmd1 ] Test for the successful execution (byevaluating the return status) of the
command, cmd1.
Bourne shell syntax
Korn Shell Syntax - A Reference Guide
Integer Numeric Conditional Testing:
Integer numeric conditional testing can also be carried use double round-brackets. This form of
syntax is more readily recognised and follows standard arithmetic rules of precedence. Unlike
the square bracketted test conditions, white-space characters are not required within the round-
bracketted conditions.
The Korn shell syntax is:
((condition))
Numeric conditions include:
If numeric variables are used within the test condition, the variable name do not to be preceded
by a dollar ($) character. The following two test conditions would be treated as being identical:
(($var==3)) Test if content of variable, var, is equal to 3.((var==3)) Test if content of variable, var, is equal to 3.
Table 9: Numeric Conditions
Condition Description
(( x == y ))((x==y))
True if the integer value of x is equal to the
integer value of y.
(( x != y ))((x!=y))
True if the integer value of x is not equal to
the integer value of y.
(( x > y ))((x>y))
True if the integer value of x is greater than
the integer value of y.
(( x < y ))((x<y))
True if the integer value of x is less than the
integer value of y.
(( x >= y ))((x>=y))
True if the integer value of x is greater than
or equal to the integer value of y.
(( x <= y ))((x<=y))
True if the integer value of x is less than or
equal to the integer value of y.
Korn Shell Syntax - A Reference Guide
Logic Testing Statement (if, then, ..., fi)
The logical state of a condition can be used to determine whether one or more command lines
should be executed. When the condition passes as true, the command lines will be invoked. If
the condition passes as false, the command lines will not be invoked.
The simplest form of locical branching is performed using the if conditional statement.
The structure of an if statement can be any of the following.
Note: The word, then, is a reserved word and must be treated as a command in its own right.
If it is to appear on the same command line as the if statement, it must be preceded by a semi-
colon to separate the two commands.
if condition_statementthen
commands to be executedfi
is the same as
if condition_statement ; thencommands to be executed
fi
For readability, it is probably better to have the word, then, on a line of its own.
if statements can be nested, as shown below. Each if must be closed by the command word fi(the word if reversed).
if condition_statement1then
command line 1command line 2
if condition_statement2then
commands_for_nested_iffi
command line 3command line 4
fi
Korn Shell Syntax - A Reference Guide
Logic Testing (if, then, ... elif ... , else ...):
Alternative command sequences can be executed based on the TRUE or FALSE return status
of a conditional test. Shown below are more forms for the if statement.
if condition_statementthen
commands to be executed if condition is TRUEelse
commands to be executed if condition is FALSEfi
Multiple conditions can be applied. For example:
if condition_statement1then
commands to be executed if condition1 is TRUEelif condition_statement2then
commands to be executed if condition2 is TRUEelif condition_statement3then
commands to be executed if condition3 is TRUEelse
commands executed if preceding conditions are FALSEfi
NOTE: Each elif is followed by the separated command word, then. The entire statement isclosed down by just one occurrence of the word fi.
Any of the conditional statements, described on the preceding pages could be used where the
words, condition_statement, appear in the examples shown above.
Korn Shell Syntax - A Reference Guide
Logic Testing (case ... esac):
As an alternative to using if then ... fi, the Korn shell supports the use of the case statement. The
syntax for the case statement is:
case value inpattern1) commands to execute
when value matchespattern1;;
pattern2) commands to executewhen value matchespattern2;;
...patternn) commands to execute
when value matchespatternn ;;
esac
Where value could be either:
A variable's contents (substituted on the command line) or a single value returned by a
command substitution.
Once value matches one of the patterns, no further attempt will be made to match any
remaining patterns within the case statement except when special syntax is used to force (notcovered within these notes).
The pattern can be any shell pattern matching structure. Multiple, alternative patterns can be
used when separated by the pipe (|) character.
Korn Shell Syntax - A Reference Guide
The patterns which can be used in a case statement are:
The last pattern, *, would normally be used as the last, catch-all, pattern match.
For example:
case "$var" ina|b) echo "contents of var contains the letter a or b"
;;[AB]) echo "contents of var contains the letter A or B"
;;*) echo "contents of var do not match any pattern above"
;;esac
Table 10: Pattern Matching is a case Statement
Pattern Description
abcd) The literal string of characters, abcd.
a|b) Either of the single characters, a or b.
a*) The letter a followed by zero or more (of any)
characters.
a*|A*) Either the letter a or the letter A followed by zero or
more occurrences of any character
[!aA]*) A string of 1 or more occurrences of any character
where the first character is not the letter a or A.
a???) A four-character string of characters where the first
character is the letter a.
\)) A literal closing round bracket, ).
*) Any number (zero or more) of any character.
Korn Shell Syntax - A Reference Guide
Loops (while, until):
The syntax for a loop is described on this and the following page. It is permitted for loops to be
nested.
while conditiondo
command1 ... commandndone
Where condition can be any valid test condition. The loop will continue to be executed
while the condition passes as TRUE.
until conditiondo
command1 ... commandndone
Where condition can be any valid test condition. The loop will continue to be executed until
condition is TRUE.
Two, special, conditional statements are available with while and until loops. These
conditional statements are the words: true and false.
In effect, they are commands that return either a zero (true) or non-zero (false) value,
respectively. So long as the state is either true or false, the loop will continue to be executed.
For example, in a while true loop, the commands, within the loop, will be executed until a false
state is encountered by the shell. This, false, state could be an interrupt (Ctrl-C) or a command's
return status which shows the command failed.
Korn Shell Syntax - A Reference Guide
Loops (for):
A for loop will continue to execute for as many times as there are arguments in the argument
list. As mentioned on the previous page, loops can be nested.
for variable in argument_listdo
command1 ... commandndone
For example, the following loop will execute 5 times because there are 5 arguments in the
argument_list.
for variable in one two three four fivedo
echo "$variable"done
The argument_list can be one or a combination of the following structures:
• list of args A literal list of arguments.
• a* A list of arguments created by filename substitution.
• $var A literal list of arguments created by variable substitution
• $(command) A literal list of arguments created by command substitution.
Korn Shell Syntax - A Reference Guide
Breaking out of a Loop:
To break out of a loop, the command word break is used. Command execution will continue
with the first command line found after the end of the loop (after the word, done).
If loops have been nested, it is possible to break out of the current and any previous, nested,
loops by following the word break with the number of loops to break out of.
while truedo command1
for variable in one two three four five do echo "$variable" if [[ "$variable" = "four" ]] then break fi done
commandn # <<<<<break to this line <<<<doneanother_command_line
while truedo command1 for variable in one two three four five do echo "$variable" if [[ "$variable" = "four" ]] then break 2 fi done commandndoneanother_command_line # <<<<break to this line <<<<
Korn Shell Syntax - A Reference Guide
Continuing around a Loop:
Within a for loop, it is possible to force the shell to return to the start of the loop and use the
next, available, argument from the argument_list.
As with the break statement, it is possible to continue at the start of a previous level of nested
loop.
for variable in one two three four fivedo echo "$variable"
for othervar in a b c ddo #<<<<continue to this line
echo "$variable $othervar" if [[ "$othervar" = "c" ]] then
continue fi
commands_inside_nested_loopdone
done
for variable in one two three four fivedo #<<<<continue to this line echo "$variable"
for othervar in a b c d edo
echo "$variable $othervar" if [[ "$othervar" = "c" ]] then
continue 2 fi
commands_in_nested_loopdone
done
When the continue is executed, no remaining commands within the current loop, with the
current argument, will be executed.
Korn Shell Syntax - A Reference Guide
Exiting from a shell script:
The exit statement is used to exit from a script.
As with break and continue, you can follow the word exit with a number. However, the
number is used as the return status value of the shell script.
For example:
$ script_name...... script runs and contains the following lineexit 0......$ echo $?0
The value, zero (0), is passed back to the parent process (the shell from which the script wasinvoked) and stored in the shell's Return Status variable ($?)
The value passed back to the parent process by the exit statement can, therefore, be used as
an error-reporting value.
The default value of the return status will be the return status value of the last command line
executed by the script unless an exit statement is supplied with a given value.
The exit statement will always force the script to terminate.
Korn Shell Syntax - A Reference Guide
An Example ShellScript - A Menu Program:
The script, shown below, provides an interactive menu from which a user can select an option.
Because the menu script uses loops, the user can make as many selections from the menu
display as they wish, up to the point where they select the Quit option.
#! /bin/ksh# Korn shell script# Script author: Context-Switch Limited, Egham, Surrey, UK# A menu program################################ DISCLAIMER DISCLAIMER ################################# This script is provided for educational purposed only.# Context-Switch does not guarantee that this script will work# It is given on the understanding that the author will not be held# responsible for any inaccuracies, disruption or loss of data# incurred through use of this script.# Use of this script implies acceptance of the above disclaimer.################################# DISCLAIMER DISCLAIMER ################################
# Use the trap facility to prevent the use of HUP, QUIT or INTtrap "echo 'Control-C cannot be used' ; sleep 1 ; clear ; continue" 1 2 3
# Start the loopwhile truedo
# clear the screen before displaying the menuclear
# Now, display the menu of choicesecho "\t MENU OF CHOICES
\t A -- \t Show the current date and time details
\t B -- \t List the contents of a directory\t \t \t (Default is $HOME )
\t Q -- \t QUIT (Leave this menu program)
\t Please type a letter (from the above choices)\t then press the RETURN key \c"
# Read user input into the variable called answerread answer
# clear the screen ready for either a command action or a message displayclear
Korn Shell Syntax - A Reference Guide
# Use the case statement to compare the user-input to a matching pattern# When a match is found, take appropriate actionscase "$answer" in[Aa]*) echo "Current date and time details are:-" echo "" date ;;
[Bb]*) echo "List the contents of which directory ? " echo "(RETURN is the same as choosing $HOME )" read dir if [ -z "$dir" ] then echo "Listing $HOME" echo "" ls $HOME elif [ -d $dir ] then echo "Listing $dir" echo "" ls $dir else echo "Sorry ... That is not a valid directory name" echo "" fi ;;
[Qq]*) echo "Quitting the menu program" ; exit 0 ;;
*) echo "Please choose an option which is displayed on the menu" ;;
esac
echo ""echo "PRESS RETURN FOR THE MENU"read waitvar
done