How to keep quotes when executing a command in bash

I have a bash script that contains something similar to the following:

cmd="grep 'a b'"

echo $cmd
$cmd

      

The problem is that $ cmd for some reason strips the quotes around "a b" and executes the command like grep a b

, causing its error:

% ./test.sh
grep 'a b'
grep: b': No such file or directory

      

I've tried various combinations of quotes and escapes, but the result is always the same.

+3


source to share


2 answers


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

      

+5


source


You shouldn't use strings for this, but arrays:

cmd=( grep 'a b' )
"${cmd[@]}"

      



For an in-depth overview see BashFAQ / 050 .

+3


source







All Articles