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 $
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"
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 the value for $OPT2
might have been something that actually
was the name of an executable (though not likely in this case with
ls). Such a situation could lead to very
undesirable results.
Did you notice, in our example, that when ls
ran, it didn’t use the long format output even though we had (tried to)
set the -l
option? That shows that
$ALLOPT
was no longer set. It had
only been set for the duration of the previous command, which was the
attempt to run the (nonexistent) -h
command.
An assignment on a line by itself sets a variable for the remainder of the script. An assignment at the beginning of a line, one that has an additional command invoked on that line, sets the variable only for the execution of that command.
It’s generally a good idea to quote your assignments to a shell variable. That way you are assured of getting only one assignment and not encountering this problem.
3.129.13.201