Page Actions
Wiki Actions
User Actions
Submit This Story

KSH Operator Substitution

Just a note of Operator Substitutions in ksh/zsh……

List Of Subs

  • ${varname:-word} If varname exists and isn't null, return its value; otherwise return word.

Purpose: Returning a default value if the variable is undefined.

  Example: ${count:-0} evaluates to 0 if count is undefined.
  • ${varname:=word} If varname exists and isn't null, return its value; otherwise set it to word and then return its value.[7]

Purpose: Setting a variable to a default value if it is undefined.

  Example: ${count:=0} sets count to 0 if it is undefined.
  • ${varname:?message} If varname exists and isn't null, return its value; otherwise print varname: followed by message, and abort the current command or script. Omitting message produces the default message parameter null or not set.

Purpose: Catching errors that result from variables being undefined.

  Example: {count:?" undefined!" } prints "count: undefined!" and exits if count is undefined.
  • ${varname:+word} If varname exists and isn't null, return word; otherwise return null.

Purpose: Testing for the existence of a variable.

  Example: ${count:+1} returns 1 (which could mean "true") if count is defined.

More Usage

A cd wrapper, log dirs that I have been to into a variable:

if cd ${dirname:?"missing directory name."} then
    DIRS="$dirname ${DIRSTACK:-$PWD}"
    print $DIRS
else
    print still in $PWD.

list files in a dir if given, list files in current dir:

for filename in ${1:+$1/}* ; do
    print $filename
done

Discussion

Enter your comment
 
 
blog/2011/05/ksh_op_sub.txt · Last modified: 2011/05/05 03:08 by MeaCulpa     Back to top
Recent changes RSS feed Creative Commons License Powered by PHP Driven by DokuWiki