I have excludes as a variable, where it's meant to be a list of regexes to pass to grep:

$ echo $excludes
-e re_1 -e re_2 -e re_3...

I'd like to be able to do something like

$ my | pipeline | grep -v "${excludes}"

but this doesn't work.

I also tried using an array as in grep -v "${excludes[@]}" where each array member is "-e blah". This didn't work either.

How can I pass arguments in a programmatic way like this?

  • 2
    I think this may be one of the cases where you should not quote your variable. – Jesse_b Dec 6 '17 at 19:50
  • 1
    @Jesse_b, only works if the regexes don't contain whitespace, and they'd get used as globs too (unless set -f), which isn't likely to be good since regexes often contain the very same characters that are special in globs... – ilkkachu Dec 6 '17 at 20:24
  • Where do your regexes come from? A space-separated string like that seems fiddly if you ever happen to need regexes that contain spaces... – ilkkachu Dec 6 '17 at 20:31
  • I control the source of the regexes, so that's not an issue in this case. choroba's answer was what I needed. – Jon Cohen Dec 6 '17 at 21:25

Array works, but you need to store the options and values as separate elements:

excludes=(-e "regex1" -e "regex2")
grep -v "${excludes[@]}" ...

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.