Department of Engineering

IT Services

Shell Variables, Aliases and Functions

Variables

The shell maintains a list of variables, some used by the shell to determine its operation (for instance the PATH variable which determines where the shell will look for programs), some created by the user.

A shell variable can be given a type (just as variables in Java or Fortran can), but this isn't necessary. Typing

      pix=/usr/lib/X11/bitmaps

(note: no spaces around the `=' sign) creates a variable `pix' whose value can be accessed by preceding the name with a `$'. `cd $pix' will take you to a directory of icons. If you type

      pix=8

then pix will be treated as a number if the context is appropriate. The let command built into the shell performs integer arithmetic operations. It understands all the C operators except for ++ and --. The typeset command can be used to force a variable to be an integer, and can also be used to select the base used to display the integer, so

pix=8
let "pix=pix<<2"
echo $pix
typeset -i2 pix
echo $pix

will print 32 then 2#100000 onscreen. The let command (note that $ signs aren't necessary before the operands) uses C's << operator to shift bits 2 to the left and the typeset command makes pix into a base 2 integer.

typeset can do much else too. Look up the shell man page for a full list. Here are just a few examples

# You can control the how many columns a number occupies and whether 
# the number is right or left justified. The following
# typeset command right-justifies j in a field of width 7. 
j=1
typeset -R7 j
echo "($j)"

# Variables can be made read-only. This j=2 assignment causes an error.
typeset -r j
j=2

# String variables can be made upper or lower case.
string=FOO
echo $string
typeset -l string
echo $string

Arrays

The Korn shell and bash support one-dimensional arrays. These needn't be defined beforehand. Elements can be assigned individually (for example name[3]=diana) or en masse.

colors[1]=red 
colors[2]=green 
colors[3]=blue

echo The array colors has ${#colors[*]} elements.
echo They are ${colors[*]}

Aliases

Aliases provide a simple mechanism for giving another name to a command.

alias mv="mv -i"

runs mv -i whenever the mv command is run. Typing alias gives a list of active aliases. Note that only the first word of each command can be replaced by the text of an alias.

Functions

Functions are much as in other high level languages. Here's a simple example of a script that creates a function, then calls it.

#takes 3 args; a string, the number of the target word in the string 
#and which chars in that field you want. No error checking done.
function number {
   echo $1 | cut -d' ' -f$2 | cut -c $3 
}

echo -n "Percentage is "
# the next line prints characters 7-8 of word 1 in the supplied string
# by calling the above function
number "%Corr=57   Acc=47.68 Fred" 1 7-8

echo -n "Acc is "
number "%Corr=57   Acc=47.68 Fred"  2 5-9