Bash Shell Scripting/Intro Exercise

We will look at a few example to get a taste as to what Bash scripting can be used. Do not fret if you do not understand these just yet.

Hello World
Let's start with a simple "hello world" program:

We can either type this directly at the Bash prompt, or else save this as a file (say, ) and run it by typing   or   at the Bash prompt. (Later we will see some more sophisticated ways to create and run a Bash script file.) In either case, it will print :

$  Hello, world!

Here we have used the  symbol to indicate the Bash prompt: after , the rest of the line shows the command that we typed, and the following line shows the output of the command.

Check File
Here is a slightly more complex script:

This script tests whether there exists a file named  in the current directory, and uses an   statement to control, based on that test, which commands are run. It, too, could be typed directly at the prompt — any script can — but in this case that is not likely to be useful.

Both of the above are entirely "within Bash", in that they do not require Bash to run any external programs. (The commands,  , and   are all built-in commands, implemented by Bash itself.) But, being a shell-scripting language, a large part of Bash's purpose is to run external programs. The following script demonstrates this ability:

Here  and   are two common utility programs that, while not part of Bash, are found on most systems that have Bash. The above script assumes the presence of a default configuration file named, and checks for the presence of a configuration file named. If  exists, then the script uses the external program   to produce a "diff" (a report of the differences between, in this case, two files), so that the user can see what non-default configurations are in place. If  does not exist, then the script uses the external program   ("copy") to copy the default configuration file to.

As you can see, the external programs are run using the same sort of syntax as the built-in commands; they're both just "commands".

The above version of this script is very "verbose", in that it generates a great deal of output. A more typical script would likely not include the  commands, since users are unlikely to need this level of information. In that case, we might use the  notation to include comments that are completely ignored by Bash, and do not appear to the user. Such comments are simply informative notes for someone reading the script itself:

But the above is simply for demonstration's sake. In reality, a script this simple does not require any comments at all.