0

Say you're writing a shell script. It takes an arbitrary number of command line arguments and passes them to a command line utility. When calling that utility, each argument needs to be prefixed with a flag. What's the correct way to escape this in your script, so that the utility sees the exact same strings that the shell script does?

Concrete example: passing regular expressions to grep. You run your wrapper script:

./findit.sh needle "old socks" "spare change"

And you expect grep to be called with those arguments as match expressions:

grep haystack.txt -e needle -e "old socks" -e "spare change"

It's the -e prefix that complicates things; if it wasn't necessary, you could just use "$@". What does your script need to do to make sure that grep gets its arguments properly escaped? Is there a portable way to do this?

0

I have a working version in Bash, but it uses Bash arrays, and I strongly suspect it's not portable:

for arg in "$@"; do
  args+=("-e" "$arg")
done

grep haystack.txt "${args[@]}"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.