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. - RANDOM :-
- a random number
for i in 1 2 3 do echo $RANDOM is a random number done
- 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
word1=one word2=two number=1
The variableword$number
has the value one but how can the value be accessed? If you tryecho $word$number
or evenecho ${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 useeval 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 oflet a="a<<2+3"
- note that this variant saves on quotemarks.[[ -f /etc/passwd ]] echo the passwd file exists
is another way of doingif [ -f /etc/passwd ] then echo the passwd file exists fi
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)) do echo $i done
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 characterfor word in four six sly do if [[ $word == ?[aeiou]? ]] then echo $word is 3 letters long with a central vowel else echo $word is not 3 letters long with a central vowel fi done
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.newfile=$(mktemp)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
newfile=$(mktemp) trap "echo Removing $newfile ; rm -f $newfile" 0 sleep 100