Easy steps for optimizing shell scripts

Speedier Scripts

Author(s):

Shell scripts are often written for simplicity rather than efficiency. A closer look at the processes can lead to easy optimization.

A shell script is essentially a sequence of commands and branches. Listing 1 shows a typical example. query.sh has all the basic components of a shell script. It contains keywords such as if, then, else, and fi; shell built-in commands such as echo and read; the square bracket; and last but not least, an external command (/bin/echo).

The calls to echo and /bin/echo behave differently, although they give you the same results. To see the difference, call the script twice while monitoring the shell with the command strace.

Listing 2 shows the first pass; Listing 3 uses Strace to display the corresponding output. At the start, the system creates a new shell process with a process identifier (PID) of 2489, which is responsible for processing the script. If you say y at the prompt, the output appears and the script is terminated (Listing 3, last line).

[...]