Shell Scripting Fundamentals

The ability to execute commands from the command line provides a great deal of power and efficiency, but executing common commands can get repetitive. In these cases, shell scripts allow groups of commands to be executed together with a single command.

As a very simple example of how to execute shell scripts, lets repeat the "Hello World" example from the previous section.

First, create a file named "myscript.sh" with the following contents:

#!/usr/bin/bash
echo Hello World!

The first line of this file is called the shebang, which starts with #! followed by the path to the interpreter that should execute this script, /usr/bin/bash.

Now, you can execute this script using the bash command, by executing bash myscript.sh as follows:

·
·
·
·
·
·
·
ninja$:·bash·myscript.sh
Hello·World!
ninja$:··

In this example the bash command is used to execute the commands contained in myscript.sh.

Shell scripts can also be executed directly by calling the full path to the script. If the script is location in the current working directory, then the script name can be prefixed with a ., which is an alias to the current working directory a shortcut. Let's try:

·
·
·
·
·
·
·
ninja$:·./myscript.sh
bash:·./myscript.sh:·Permission·denied
ninja$:··

Whoa, what happened? Executing files can present security risks, so permission must be explicitly granted before a script can be executed. This is accomplished using the chmod command as follows:

·
·
·
·
·
·
·
·
ninja$:·chmod·u+x·myscript.sh
ninja$:··

In short, chmod is short for "change mode". In this case we want to add executable (x) permission to the current user, which is stated as "u+x". Finally, we state the name of the file to apply this change to.

Now, let's try executing the script again:

·
·
·
·
·
·
·
ninja$:·./myscript.sh
Hello·World!
ninja$:··

With that, we have enough background information to start learning the fundamentals of working with the command-line in the following sections.