8.13 Writing Shell Scripts
So far we have focused exclusively on the interactive nature of the Bash shell. By interactive we mean manually entering commands at the prompt one by one and executing them. In fact, this is only a small part of what the shell is capable of. Arguably one of the most powerful aspects of the shell involves the ability to create shell scripts. Shell scripts are essentially text files containing sequences of statements that can be executed within the shell environment to perform tasks. In addition to the ability to execute commands, the shell provides many of the programming constructs such as for and do loops and if statements that you might reasonably expect to find in a scripting language.
Unfortunately a detailed overview of shell scripting is beyond the scope of this chapter. There are, however, many books and web resources dedicated to shell scripting that do the subject much more justice than we could ever hope to achieve here. In this section, therefore, we will only be providing a very small taste of shell scripting.
The first step in creating a shell script is to create a file (for the purposes of this example we name it simple.sh) and add the following as the first line:
#!/bin/sh
The #! is called the “shebang” and is a special sequence of characters indicating that the path to the interpreter needed to execute the script is the next item on the line (in this case the sh executable located in /bin). This could equally be, for example, /bin/csh or /bin/ksh if either were the interpreter you wanted to use.
The next step is to write a simple script:
#!/bin/sh
for i in *
do
echo $i
done
All this script does is iterate through all the files in the current directory and display the name of each file. This may be executed by passing the name of the script through as an argument to sh:
$ sh simple.sh
In order to make the file executable (thereby negating the need to pass it through to the sh command) the chmod command can be used:
$ chmod +x simple.sh
Once the execute bit has been set on the file’s permissions, it may be executed directly. For example:
$ ./simple.sh