Shell scripts are a convenient way of doing all sorts of tasks: collecting data, searching for a word or phrase in a text and many other useful things. The following example shows a small shell script that prints a text:
Example 18.1. A Shell Script Printing a Text
#!/bin/sh# Output the following line:
echo "Hello World"
The first line begins with the Shebang characters
( | |
The second line is a comment beginning with the hash sign. It is recommended to comment difficult lines to remember what they do. | |
The third line uses the built-in command echo to print the respective text. |
Before you can run this script you need some prerequisites:
Every script should contain a Shebang line (this is already the case with our example above.) If a script does not have this line, you have to call the interpreter yourself.
You can save the script wherever you want. However, it is a good idea
to save it in a directory where the shell searches for it. The search
path in a shell is determined by the environment variable
PATH. For example, save it in the directory
~/bin/ under the name
hello.sh.
The script needs executable permissions. Set the permissions with the following command:
chmod +x ~/bin/hello.sh
If you have fullfilled all of the above prerequisites, you can execute
the script with either ~/bin/hello.sh or
hello.sh. The first call uses an absolute path whereas
the second one searches for the command in each directory given by the
PATH environment variable.