Running Commands from a Variable

Problem

You want to run different commands in your script depending on circumstances. How can you vary which commands run?

Solution

There are many solutions to this problem—it’s what scripting is all about. In coming chapters we’ll discuss various programming logic that can be used to solve this problem, such as if/then/else, case statements, and more. But here’s a slightly different approach that reveals something about bash. We can use the contents of a variable (more on those in Chapter 5) not just for parameters, but also for the command itself.

FN=/tmp/x.x
PROG=echo
$PROG $FN
PROG=cat
$PROG $FN

Discussion

We can assign the program name to a variable (here we use $PROG), and then when we refer to that variable in the place where a command name would be expected, it uses the value of that variable ($PROG) as the command to run. The bash shell parses the command line, substitutes the values of its variables and takes the result of all the substitutions and then treats that as the command line, as if it had been typed that way verbatim.

Warning

Be careful about the variable names you use. Some programs such as InfoZip use environment variables such as $ZIP and $UNZIP to pass settings to the program itself. So if you do something like ZIP='/usr/bin/ zip', you can spend days pulling your hair out wondering why it works fine from the command line, but not in your script. Trust us. We learned this one the hard way. Also, RTFM.

See Also

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.