Reputation: 24227
I have a bash script which contains something similar to the following:
cmd="grep 'a b'"
echo $cmd
$cmd
The issue I am having is that the $cmd, for some reason, removes the quotes around the 'a b', and executes the command as grep a b
, causing it to error:
% ./test.sh
grep 'a b'
grep: b': No such file or directory
I have tried various combinations of quotes and escaping, but the result is always the same.
Upvotes: 3
Views: 65
Reputation: 362107
The best place to store commands is in functions. Rule of thumb: Variables are for data; functions are for commands.
cmd() {
grep 'a b'
}
...
cmd
Upvotes: 5
Reputation: 46903
You shouldn't use strings for that, but arrays:
cmd=( grep 'a b' )
"${cmd[@]}"
See BashFAQ/050 for in-depth overview.
Upvotes: 3