7.3.1. Shell-scripts

A shell script is in fact nothing more than a serie of commands which are put in one file, so that they easily can be executed more than once, or without user-control. You can execute that file as

bash [options] script [arguments]

This runs the script (using bash) as a subshell with the given arguments. Another way is to put in the file itself how it should run. Therefore we put the following line as first line (shebang line):

#!/bin/bash

Then, we can use the script just as a command, if the script has execute and read permission. If the directory where the script is located, is in PATH (see here) , then the script will be found automatically. Otherwise we have to give the (full or relative) pathname.

As said, you can use in a script all commands learnt (and not-learnt). There are some commands however which are almost exclusively used in script and are seldom used from the command line. We will describe some of them in the next sections. But remember that you can use them from the commandline. After all, the login shell is an ordinary shell.

First we give to special commands:

#

this command neglects everything that follows on the same line (except the previous mentioned #! on the first line). This is used to put comments in the script.

:

the command does nothing. It can be used on a place where you have to put a command according to the syntax, but doesn’t want to do anything. A typical use is to create an endless loop using while:

while :

Bash also accepts options. Some usefull for debugging or in larger scripts are mentioned already here. These options can be set on the invocaton of bash on the command line:

bash -x script

or in the shebang line:

#!/bin/bash -eu

They can also be set and unset in the script itself:

set +x  # turn off printing of each line executed
        # also if the invovation is 'bash -x'
...some code

set -x  # turn on debugging for next lines
...some code with a prpblem

set +x  # turn off debugging again