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 20.1. A Shell Script Printing a Text
#!/bin/sh# Output the following line:
echo "Hello World"
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 manually.
You can save the script wherever you want. However, it is a good idea
to save it in a directory where the shell can find it. The search path
is determined by the environment variable PATH. Usually
a normal user does not have write access to
/usr/bin. Therefore it is recommended to save your
scripts in the directory ~/bin/. The above example
gets 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 just
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.