Functions

Define some shell code by name and store it in the shell's memory, to be invoked and run later.

Function Syntax

The first form is prefered.

function fname {
  shell commands
}

or...

fname () {
  shell commands
}

Example:

function termsettings {
  echo "Terminal settings are:"
  echo "TERM = $TERM"
  echo "EDITOR = $EDITOR"
  echo "stty settings:"
  stty -a
}

Function Variables

Shell functions use positional parameters just like shell scripts do.

Example

(from Learning the Korn Shell, p. 93)

function afunc {
  print in function $0: $1 $2
  var1="in function"
}

var1="outside of function"
print var1: $var1
print $0: $1 $2
afunc funcarg1 funcarg2
print var1: $var1
print $0: $1 $2

Command Precedence

Shell looks for the definition of a command in the following order:

  1. Keywords (e.g. function, if, for)
  2. Aliases
  3. Built-ins (e.g. cd, whence)
  4. Functions
  5. Shell scripts and other executable programs (search in directories listed in PATH)

To see the source of a command, type

whence -v commandname


Shell Input

read

The read command reads one line of text from the standard input, and assigns it to the specified variable(s).


More Control-Flow Commands

while

while test-command
do
  commands
done

Example:

while read line
do
  echo $line >> outfile
done

until

until test-command
do
  commands
done

Example:

secretname="Snow White"
name=none
until [[ ${name} = ${secretname} ]]
do
  echo "Guess a name: \c"
  read name
done
echo "Good guess!"

Interrupting Loops

The break and continue commands may be used to skip over parts of the loop.