Example Bash script
The mysystem.sh script below executes some well-known commands (date, w, uname, uptime) to display information about you and your machine.
tom:~> cat -n mysystem.sh
3 echo "This is information provided by mysystem.sh. Program starts now."
5 echo "Hello, $USER"
8 echo "Today's date is `date`, this is week `date +"%V"`."
11 echo "These users are currently connected:"
12 w | cut -d " " -f 1 - | grep -v USER | sort -u
15 echo "This is `uname -s` running on a `uname -m` processor."
18 echo "This is the uptime information:"
22 echo "That's all folks!"
A script always starts with the same two characters, "#!". After that, the shell that will execute the commands following the first line is defined. This script starts with clearing the screen on line 2. Line 3 makes it print a message, informing the user about what is going to happen. Line 5 greets the user. Lines 6, 9, 13, 16 and 20 are only there for orderly output display purposes. Line 8 prints the current date and the number of the week. Line 11 is again an informative message, like lines 3, 18 and 22. Line 12 formats the output of the w; line 15 shows operating system and CPU information. Line 19 gives the uptime and load information.
Both echo and printf are Bash built-in commands. The first always exits with a 0 status, and simply prints arguments followed by an end of line character on the standard output, while the latter allows for definition of a formatting string and gives a non-zero exit status code upon failure.
This is the same script using the printf built-in:
tom:~> cat mysystem.sh
printf "This is information provided by mysystem.sh. Program starts now."
printf "Hello, $USER.\n\n"
printf "Today's date is `date`, this is week `date +"%V"`.\n\n"
printf "These users are currently connected:\n"
w | cut -d " " -f 1 - | grep -v USER | sort -u
printf "This is `uname -s` running on a `uname -m` processor.\n\n"
printf "This is the uptime information:\n"
printf "That's all folks!\n"
Creating user friendly scripts by means of inserting messages is treated in Chapter 8.
|Standard location of the Bourne Again shell|
This implies that the bash program is installed in /bin.
|If stdout is not available|
If you execute a script from cron, supply full path names and redirect output and errors. Since the shell runs in non-interactive mode, any errors will cause the script to exit prematurely if you don't think about this.
The following chapters will discuss the details of the above scripts.