Department of Engineering

IT Services

Advanced Features and Speed-ups

There are many mentioned in the shell man page. Here are just a few:-

getopt :-
Helps parse command line options.
variable substitution :-
`X=${H:-/help}' sets the variable X to the value of H if H exists, otherwise it sets X to /help.
a random number
for i in 1 2 3
  echo $RANDOM is a random number
Regular Expressions :-
Commands like grep and sed make use of a more sophisticated form of pattern matching than the '*' and '?' wildcard characters alone can offer. See the manual page for details - on my system typing ``man 5 regexp'' displays the page.

Eval :-
Consider the following
The variable word$number has the value one but how can the value be accessed? If you try echo $word$number or even echo ${word$number} you won't get the right answer. You want $number processed by the shell, then the resulting command processed. One way to do this is to use eval echo \$word$number - the \ symbol delays the interpretation of the first $ character until eval does a second pass.

Alternative notations :-
((a=a<<2+3)) is the equivalent of let a="a<<2+3" - note that this variant saves on quotemarks.

  [[ -f /etc/passwd ]]
     echo the passwd file exists
is another way of doing

  if [ -f /etc/passwd ]
     echo the passwd file exists
or you could use the logical && operator, which like its C cousin only evaluates the second operand if the first is true.
  [ -f /etc/passwd ] && echo the passwd file exists

Bash features:-
C-like for loops are possible.
for((i=1; $i<3; i=i+1))
  echo $i
Regular expressions (wildcard characters etc) can be used in some comparisons. In the following, ?[aeiou]? is a regular expression that matches a character followed by one of a, e, i , o ,u, followed by a character
for word in four six sly
  if [[ $word == ?[aeiou]? ]]
    echo $word is 3 letters long with a central vowel
    echo $word is not 3 letters long with a central vowel

Signals and Temporary Files

A script may need to create temporary files to hold intermediate results. The safest way to do this is to use mktemp which returns a currently unused name. The following command creates a new file in /tmp.
If a script is prematurely aborted (the user may press ^C for example) it's good practise to remove any temporary files. The trap command can be used to run a tidy-up routine when the script (for whatever reason) exits. To see this in action start the following script then press ^C
  trap "echo Removing $newfile ; rm -f $newfile" 0
  sleep 100