Chapter 8 - The Bourne Again Shell

Quiz

1. Why does the fact that Bash provides arithmetic capability natively improve the run time of shell scripts so dramatically?
In other shells, you must use the expr command to do arithmetic. So for each and every calculation you perform, you fork a new process to run expr from the shell script. If your script performs a few calculations you may not notice the difference, but in a loop that executes hundreds or thousands of times you would!
2. Why are braces required around list variables?
Braces are required around list variables to distinguish the variable from other shell operators or text that is  adjacent to the variable specification, thus preventing the shell from misinterpret the meaning.
3. Do all Bourne Shell scripts work in Bash?
Yes, Bash is a superset of the Bourne Shell.
4. Do all Bash scripts work in the Korn Shell?
No, Bash provides features not found in the Korn Shell.
5. What shell variable contains the directory stack?
Bash maintains the directory stack in an array called $DIRSTACK.

Exercise

The track script presented in Chapter 5 runs as is under Bash. However, it makes use of the expr UNIX command to do its arithmetic calculations. Modify track to use Bash arithmetic, and compare its speed of execution with that of the original version. You may wish to use the UNIX time command (described in Chapter 3) to measure the differences if nothing ěfeelsî significantly different. [level: easy]
The learning is in the doing with this exercise.

Project

Write a Bash script called mv (which replaces the UNIX command mv) that tries to rename the specified file (using the UNIX command mv), but if the destination file exists, instead creates an index numberóa sort of version numberóto append to the destination file. So if I type

        $ mv a.txt b.txt

but b.txt already exists, mv will move the file to b.txt.1. Note that if b.txt.1 already exists, you must rename the file to b.txt.2, and so on, until you can successfully rename the file with a name that does not already exist. [level: medium]

This script will run much faster than a version written for another shell because of the option to use internal arithmetic (if you had to rename a file to b.txt.27, you would execute expr 26 times before the command would complete!). The only tricky part is to make sure when your script executes mv, that it uses the system version rather than recursively executing itself.