Forgetting Quotes Leads to “command not found” on Assignments

Problem

Your script is assigning some values to a variable, but when you run it, the shell reports “command not found” on part of the value of the assignment.

$ cat goof1.sh
#!/bin/bash -
# common goof:
#  X=$Y $Z
# isn't the same as
#  X="$Y $Z"
#
OPT1=-l
OPT2=-h
ALLOPT=$OPT1 $OPT2
ls $ALLOPT .
$
$ ./goof1.sh
goof1.sh: line 10: -h: command not found
aaa.awk cdscript.prev ifexpr.sh oldsrc xspin2.sh
$

Solution

You need quotes around the righthand side of the assignment to $ALLOPT. What is written above as:

ALLOPT=$OPT1 $OPT2

really should be:

ALLOPT="$OPT1 $OPT2"

Discussion

It isn’t just that you’ll lose the embedded spaces between the arguments; it is precisely because there are spaces that this problem arises. If the arguments were combined with an intervening slash, for example, or by no space at all, this problem wouldn’t crop up—it would all be a single word, and thus a single assignment.

But that intervening space tells bash to parse this into two words. The first word is a variable assignment. Such assignments at the beginning of a command tell bash to set a variable to a given value just for the duration of the command—the command being the word that follows next on the command line. At the next line, the variable is back to its prior value (if any) or just not set.

The second word of our example statement is therefore seen as a command. That word is the command that is reported as “not found.” Of course it is possible that ...

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.