Linux: Controlling the Flow of Execution

In Linux bash scripts, you can control the flow of execution — the order in which the commands are executed — by using special commands such as if, case, for, and while.

These control statements use the exit status of a command to decide what to do next. When any command executes, it returns an exit status — a numeric value that indicates whether or not the command has succeeded. By convention, an exit status of zero means the command has succeeded. (Yes, you read it right: Zero indicates success!) A nonzero exit status indicates that something has gone wrong with the command.

For example, suppose that you want to make a backup copy of a file before editing it with the vi editor. More importantly, you want to avoid editing the file if a backup can’t be made. Here’s a bash script that takes care of this task:

#!/bin/sh
if cp "$1" "#$1"
then
vi "$1"
else
echo "Failed to create backup copy"
fi

This script illustrates the syntax of the if-then-else structure and shows how the exit status of the cp command is used by the if command to determine the next action. If cp returns zero, the script uses vi to edit the file; otherwise, the script displays an error message and exits.

By the way, the script saves the backup in a file whose name is the same as that of the original, except for a hash mark (#) added at the beginning of the filename.

Don’t forget the final fi that terminates the if command. Forgetting fi is a common source of errors in bash scripts.

  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus
Advertisement

Inside Dummies.com