Running Several Commands in Sequence

Problem

You need to run several commands, but some take a while and you don’t want to wait for the last one to finish before issuing the next command.

Solution

There are three solutions to this problem, although the first is rather trivial: just keep typing. A Linux or Unix system is advanced enough to be able to let you type while it works on your previous commands, so you can simply keep typing one command after another.

Another rather simple solution is to type those commands into a file and then tell bash to execute the commands in the file—i.e., a simple shell script.

Assume that we want to run three commands: long, medium, and short, each of whose execution time is reflected in its name. We need to run them in that order, but don’t want to wait around for long to finish before starting the other commands. We could use a shell script (aka batch file). Here’s a primitive way to do that:

$ cat > simple.script
long
medium
short
^D                      # Ctrl-D, not visible
$ bash ./simple.script

The third, and arguably best, solution is to run each command in sequence. If you want to run each program, regardless if the preceding ones fail, separate them with semicolons:

$ long ; medium ; short

If you only want to run the next program if the preceding program worked, and all the programs correctly set exit codes, separate them with double-ampersands:

$ long && medium && short

Discussion

The cat example was just a very primitive way to enter text into a file. We redirect the output from the command into the file named simple.script (for more on redirecting output, see Chapter 3). Better you should use a real editor, but such things are harder to show in examples like this. From now on, when we want to show a script, we’ll just either show the text as disembodied text not on a command line, or we will start the example with a command like cat filename to dump the contents of the file to the screen (rather than redirecting output from our typing into the file), and thus display it in the example.

The main point of this simple solution is to demonstrate that more than one command can be put on the bash command line. In the first case the second command isn’t run until the first command exits, and the third doesn’t execute until the second exits and so on, for as many commands as you have on the line. In the second case the second command isn’t run unless the first command succeeds, and the third doesn’t execute until the second succeeds and so on, for as many commands as you have on the line.

Get bash Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.