KSH Reference
KSH Reference
Table 2: String Variable Assignment Syntax var=value var="v1 v2 v3" var=$var2 var=$(cmd) var=`cmd` var= var[n]=value typeset -l var=Val Meaning Assign value as the contents of the variable var. Assign the three words v1 v2 v3 as the contents of the variable var. Assign the contents of variable var2 to the variable var. Assign the output of the UNIX command, cmd, as the contents of the variable var. Bourne shell equivalent of the above command output assignment (supported within the Korn shell). Assign NULL as the contents of the variable var. Assign value as the contents of the nth element of array variable var. Assign the value, val, to the variable, var, and force the contents to be displayed/substituted as lower-case (eg: val). Assign the value, val, to the variable, var, and force the contents to be displayed/substituted as upper-case (eg: VAL). Assign the value, val, to the variable, var, and set display attributes to be left-aligned, truncated to 20 characters.* Assign the value, val, to the variable, var, and set display attributes to be right-aligned, truncated to 20 characters.*
typeset -u var=Val
* NOTE: When variables are assigned Left or Right-alignment formatting, using the typeset command, the typeset display output characteristics will only be applied if the variable is quoted within double-quotes () on the shell command line. (See Variable Substitution)
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 $var ${var}text Meaning Substitute with the contents of the variable var. Substitute with the contents of the variable var and append the characters, text, to the substituted contents. Substitute with the number of characters stored in the variable var. If the content is NULL, the substitution value would be 0 (zero) If the variable has NULL contents, substitute with the alternative value, alt. The current variable contents are retained in the variable store. If the variable has NOT NULL contents, substitute with the alternative value, alt. The current variable contents are retained in the variable store. 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 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. Substitute with all elements of the array variable, var. Substitute with all elements of the array variable, 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.
${#var}
${var:-alt}
${var:+alt}
${var:=alt}
${var:?err}
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 1 This is line 2 The output of quoted and unquoted variable substitions would be as shown below: $ echo $myvar This is line 1 This is line 2 $ echo "$myvar" This is This is
line line
1 2
$@ $#
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.$$
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.
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 with your 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 le on the command line: $ command < file_name 2. Redirect stdout to the named le (le_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 le, 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 le, on the command line: $ command 2> file_name 5. Append stderr to the named le, le_name, on the command line: $ command 2>> file_name
Shell Pipelines
Data output can be transferred to become another commands 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.
#(open file for output) #(store output) #(store output) #(close file)
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> ]]
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: Table 6: Conditional Expressions Condition -a file -b file -c file -d file -f file -g file -h file -k file -n string -o option -p file -r file -s file -t file_descriptor -u file True if le exists True if file exists and is a block special file. True if file exists and is a character special file. True if file exists and is a directory. True if file exists and is an ordinary file. True if file exists and is has its setgid bit set. True if file exists and is a symbolic link. True if file exists and is has its sticky bit set. True if length of string is non-zero. True if option named option is on. True if file exists and is a fifo special file or a pipe. True if file exists and is readable by current process. True if file exists and has size greater than zero. True if file descriptor number file_descriptor is open and associated with a terminal device. True if file exists and is has its setuid bit set. Description
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 -w file -x file Description True if file exists and is writable by current process. 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. True if length of string is zero. True if file exists and is a hidden directory. True if file exists and is a symbolic link True if file exists and is owned by the effective user ID of the current process True if file exists and its group matches the effective group ID of this process. True if file exists and is a socket. True if file1 exists and is newer than file2 True if file1 exists and is older than file2 True if file1 and file2 both exist and refer to the same file. True if string, str, matches the pattern. The pattern can be a literal string or consist of shell lename substitution meta-characters or combination. True if string, str, does not match pattern True if str1 comes before str2 based on the ASCII value of their characters True if str1 comes after str2 based on the ASCII value of their characters True if str1 comes before str2 based on the ASCII value of their characters True if exp1 is equal to exp2. True if exp1 is not equal to exp2. True if exp1 is less than exp2. True if exp1 is greater than exp2. True if exp1 is less than or equal to exp2. True if exp1 is greater thanor equal to exp2.
-z string -H file -L file -O file -G file -S file file1 -nt file2 file1 -ot file2 file1 -ef file2 str = pattern
str != pattern str1 < str2 str1 > str2 str < pattern exp1 -eq exp2 exp1 -ne exp2 exp1 -lt exp2 exp1 -gt exp2 exp1 -le exp2 exp1 -ge exp2
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 (expression) ! expression expr1 && expr2 Description True, if expression is true. The round-brackets are used to group expressions. True if expression is false. ! is syntax used by the shell to represent NOT. True, if both expr1 and expr2 are true. && is the syntax for Logical-AND Note: This is Korn shell specific syntax. When used with the test condition, is only applicable with the command words test or [[ ... ]] (See Bourne shell compatible syntax, below) True, if either expr1 or expr2 is true. || is the syntax for Logical-OR Note: This is Korn shell specific syntax. When used with the test condition, is only applicable with the command words test or [[ ... ]] (See Bourne shell compatible syntax, below) Bourne shell compatible True, if both expr1 and expr2 are true. Note: This is Bourne shell syntax. When used with the test condition, is only applicable with the command words test or [ ... ] Bourne shell compatible True, if either expr1 or expr2 is true. || is the syntax for Logical-OR Note: This is Bourne shell syntax. When used with the test condition, is only applicable with the command words test or [ ... ]
expr1 || expr2
expr1 -a expr2
expr1 -o expr2
[[ cmd1 ]]
[ cmd1 ]
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 ]] [[ condition1 || condition2 ]] Bourne shell syntax: [ condition1 -a condition2 ] [ condition1 -o condition2 ]
The -a and -o clauses can not be used inside the Korn shell-specific, [[ ... ]], test statement.
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.
The patterns which can be used in a case statement are: Table 10: Pattern Matching is a case Statement Pattern abcd) a|b) a*) a*|A*) [!aA]*) a???) \)) *) Description The literal string of characters, abcd. Either of the single characters, a or b. The letter a followed by zero or more (of any) characters. Either the letter a or the letter A followed by zero or more occurrences of any character A string of 1 or more occurrences of any character where the first character is not the letter a or 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.
The last pattern, *, would normally be used as the last, catch-all, pattern match. For example: case "$var" in a|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
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_list do command1 ... commandn done 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 five do echo "$variable" done The argument_list can be one or a combination of the following structures: list of args a* $var $(command) A literal list of arguments. A list of arguments created by lename substitution. A literal list of arguments created by variable substitution A literal list of arguments created by command substitution.
for variable in one two three four five do #<<<<continue to this line echo "$variable" for othervar in a b c d e do echo "$variable $othervar" if [[ "$othervar" = "c" ]] then continue 2 fi commands_in_nested_loop done done When the continue is executed, no remaining commands within the current loop, with the current argument, will be executed.
#! /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 INT trap "echo 'Control-C cannot be used' ; sleep 1 ; clear ; continue" 1 2 3 # Start the loop while true do # clear the screen before displaying the menu clear # Now, display the menu of choices echo "\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 answer read answer # clear the screen ready for either a command action or a message display clear
# Use the case statement to compare the user-input to a matching pattern # When a match is found, take appropriate actions case "$answer" in [Aa]*) echo "Current date and time details are:-" echo "" date ;; [Bb]*) echo echo read if [ then "List the contents of which directory ? " "(RETURN is the same as choosing $HOME )" dir -z "$dir" ]
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]*) *) esac echo "" echo "PRESS RETURN FOR THE MENU" read waitvar done echo "Quitting the menu program" ; exit 0 ;; echo "Please choose an option which is displayed on the menu" ;;