Shell
5.2. Shell#
The shell provides an enormously powerful text based interface for programmers to interact with the Unix operating system. We already discussed the shell when describing the key abstractions of Unix, so you know key unix commands, redirection, pipes, process tree, etc… One very useful feature we have not touched on yet is shell scripts. A shell script is a file that contains the same commands that you could type directly into a shell, and it is frequently used by developers to automate tasks. As a simple example consider the shell script shown in Listing 5.1 that automates running a set of tests passed to the script, where it reports how many tests succeeded, prints out the failures, including tests that took more than a timeout to run.
1#!/bin/bash
2TIMEOUT_SECONDS=5
3
4all_tests=$@
5test_count=$#
6fail_count=0
7
8for test_file in $all_tests
9do
10 echo "===== ${test_file} ====="
11 rm -f testfs # Tidy up from previous tests
12 timeout ${TIMEOUT_SECONDS} ${test_file}
13 rc=$?
14 if [ ${rc} -eq 0 ]
15 then
16 echo "PASS"
17 elif [ ${rc} -eq 124 ]
18 then
19 echo "FAIL (${TIMEOUT_SECONDS} second timeout)"
20 fail_count=$((fail_count + 1))
21 else
22 echo "FAIL (rc = ${rc})"
23 fail_count=$((fail_count + 1))
24 fi
25done
26
27echo "${fail_count} out of ${test_count} tests failed."
The first line in the file tells the OS to run this using the bash shell. Line 3 gets the list of tests to run. For each test, in it prints the name of the test, runs the test (line 10) with a timeout value specified on line 1. Lines 12-21 prints out for each test if the program ran correctly, and if not accumulates the number of failed tests.
This is just a simple example of the kind of automation you can do with shell scripts. For more detail on all the special variables… please run “man bash” and search for “PARAMETERS”. There are many wonderful tutorials (e.g., this one) and cheat sheets online. Also, for more information about terminals and shells, this information is covered in much more detail in this companion book.