BASH Execute a Command in a Variable – with Quotes!

BASH Execute a Command in a Variable – with Quotes!

Just recently I encountered a situation where I was using a BASH script to evaluate some input and then pass a boat-load of parameters to another executable. It just so happened that one of the parameters I was pasisng was a variable that had a space in it. So… –myvar “my spacey attribute”.

This command would work great when I ran the command myself, but as soon as I tried to execute the command in my BASH script, the blasted thing would not evaluate. The executable I was trying to pass the attribute with spaces totally ignored my quotes around the attribute value and evaluated my spaces as the beginning of another attribute. It was frustrating to the extreme! I tried all kinds of different quotation combinations. I re-wrote the same bit of code several different times in several different ways all with the same crappy results.

After much Google hunting, I came accross a post where someone suggested to another to use “eval” to correct a problem he was having with a parsed command (similar to what I was doing, but still quite different). The suggestion was shot down as being “too much” for that particular case, but I had never used “eval” before so I looked it up, and turns out it does exactly what I was needing and then some! “eval” is built int BASH so if you have BASH, you have eval. Here’s my example…

Using this:

myCommand="$myExecutable --mode install ";
myCommand+="--directory /path/to/mydir/ ";
myCommand+="--password 'my password' ";

This did NOT work:

# now run the command

but this DID work:

# now run the command
eval $myCommand;

So, if you ever find yourself trying to figure out why your command isn’t parsing correctly and pulling your hair out over it, try the “eval” command. I hope this helps someone and saves you the hours of frustration it would have saved me!!

Leave a Reply

Your email address will not be published. Required fields are marked *

17 + 17 =