Complete Communications Engineering

One of the most important jobs of a Linux shell is interpreting commands.  Commands can be typed into a console manually, but this is very inefficient when many commands are needed or the same commands must be repeated many times.  Linux shell scripts can be used to automate commands.  A shell script is a file that contains commands.  When a shell script is run, the Linux shell reads the commands and interprets them as if they were typed.  Modern shells support many advanced features that allow for a wide variety of complex behaviors.  One disadvantage is that shell scripts are interpreted at run-time so very complex scripts can be slow to execute.

There are a number of ways to run a shell script.  One is to invoke the shell program directly.  For example, if using the Bourne shell (sh) the following command could be used to run a shell script (script.sh):

> sh script.sh

Another way is to make the shell script file executable and run it as an executable program.  The chmod program can be used to make a shell script executable:

> chmod +x script.sh

When the script file is executable, it can be run like any other executable.  If the script is in a folder that is in the PATH environment variable, it can be run from any folder by just typing the name of the script.  If it’s not in the environment’s PATH, the script can only be run by specifying a path to it.  If the script is in the current folder, the following command will execute it:

> ./script.sh

Executable scripts require a hash-bang header.  The header must be the first entry in the script file, so the first two bytes of the file are “#!”.  Using this method, scripts can be run like any other program.  The Linux kernel can distinguish between scripts and binary executables by checking the first two bytes of the program it’s running.  The characters immediately after the hash-bang header tell which interpreter should be used to run the script.  The following example shows a hash-bang header for the Bourne shell (sh):

script.sh

#!/bin/sh

echo “Interpreted by /bin/sh”

output:

> ./script.sh

Interpreted by /bin/sh