Command-Line Options

Positional Parameters

Command-line options may be referenced with the usual positional parameters

Problem: if options are truly optional, how do we keep track of what the positional parameters represent?

shift

The shift command has the effect of shifting all of the positional parameters over by a specified number

Option Processing

The getopts built-in handles multiple complex options.

getopts

getopts expects 2 arguments:

  1. a string containing letters and colons
    1. each letter represents a valid option
    2. a letter followed by a colon indicates that that option expects an argument
    3. a colon as the 1st character indicates that invalid options should not be reported
  2. a variable

If getopts successfully retrieves an option,

Example
(from Learning the Korn Shell, p. 163)

while getopts ":cgl:o:O" opt; do
  case $opt in
    c ) do_link=false ;;
    g ) debug="-g" ;;
    l ) link_libs="$link_libs -l $OPTARG" ;;
    o ) exefile="-o $OPTARG" ;;
    O ) opt=true ;;
    \? ) print "usage: $0 [-cgO] [-l lib] [-o file] files"
    return 1 ;;
  esac
done
shift $(($OPTIND - 1))

Integer Arithmetic

Arithmetic Expressions

Korn shell interprets words within $(( and )) as arithmetic expressions.

Alternative: use the expr unix command

Arithmetic Conditionals

Korn shell interprets words within (( and )) as arithmetic condition tests.

Arithmetic Variables and Assignment

Arithmetic variables may be defined and assigned values one of two ways:

Must quote special characters and expressions that contain spaces

Arrays

Ordered one-dimensional list of <= 1024 elements

Variable Specifications

The typeset command is used to

Without options, typeset varname inside a function will make variable varname local to that function.

Without specified varname(s), the shell prints a list of variables for which the given option is turned on.

String Formatting

Calling typeset with string formatting options imposes a format on the contents of the named variable(s). Options are cumulative.

Type & Attribute Options

Function Options

These all relate to functions, not variables