UNIX Korn Shell
Contents |
A collection of tips and tricks for UNIX Korn Shell (KSH).
Modifiers
The value of variables can be modified before being used if the variable name is enclosed within braces ("{" and "}") and the appropriate modifier characters are used:
Name | Description |
---|---|
${var-string} | Use the value of var unless it’s empty; then use string. |
${var=string} | Use the value of var unless it’s empty; then assign string to var and use it. |
${var?string} | Use the value of var unless it’s empty; then print string as an error message end terminate the shell. |
${var+string} | Use the value of var unless it’s NOT empty; then use string. |
${var#wildpat} | Use the value of var after removing any characters from the front of the value which match the wildcard pattern wildpat. The characters matched by the pattern are the shortest possible string. |
${var##wildpat} | Same as above, but the match is the longest possible string. |
${var%wildpat} | Same as #, but this one trims from the end of the string instead of the beginning. It matches the shortest possible string. |
${var%%wildpat} | Same as above, but the match is the longest possible string. |
$$ | The process id of the shell. This is usually used for temporary filenames, such as /tmp/$0.$$. |
$! | The process id of the last job to be executed in the background. |
$0 | Name of the shell script that is running. It may include a pathname, so it would be more appropriate to use basename, or a similar construct, to remove the directory component before using it in an out- put statement.
#!/bin/ksh PROG=$(basename $0) USAGE="Usage: $PROG fromfile tofile ..."or #!/bin/ksh PROG=${0##*/} USAGE="Usage: $PROG fromfile tofile ..." |
$1-$n | These represent the command line parameters provided by the user of the script when it was executed. |
$# | The number of command line parameters. |
"$@" | The values of the command line parameters with double quotes around individual parameters.
The last three variables, $n, $#, and $@, are specific shortcuts of the general technique of accessing elements of an array: |
${array[n]} | This accesses the nth element of array. |
${array[@]} | This accesses all of the elements of array. |
${#array[@]} | This provides the number of elements in array. |