These work as advertised:
grep -ir 'hello world' .
grep -ir hello\ world .
These don't:
argumentString1="-ir 'hello world'"
argumentString2="-ir hello\\ world"
grep $argumentString1 .
grep $argumentString2 .
Despite 'hello world'
being enclosed by quotes in the second example, grep interprets 'hello
(and hello\
) as one argument and world'
(and world
) as another, which means that, in this case, 'hello
will be the search pattern and world'
will be the search path.
Again, this only happens when the arguments are expanded from the argumentString
variables. grep properly interprets 'hello world'
(and hello\ world
) as a single argument in the first example.
Can anyone explain why this is? Is there a proper way to expand a string variable that will preserve the syntax of each character such that it is correctly interpreted by shell commands?
grep $argumentString1 .
expands togrep -ir hello world .
. – Masticategrep $argumentString2 .
expands togrep -ir hello\ world .
(i.e. the backslash is part of the second argument to grep). – Masticate