0

I am trying to use a variable to store grep's options:

#!/bin/sh
set -xe

GREP_OPTS="-e \"test this\""
echo "I want to test this." | grep $GREP_OPTS

Output:

+ GREP_OPTS=-e "test this"
+ echo I want to test this.
+ grep -e "test this"
grep: this": No such file or directory

how can I make this work?

benji
  • 2,331
  • 6
  • 33
  • 62
  • FYI, `set -e` is... err, let's say *controversial*. I'd suggest avoiding its use until answers to the exercises in [BashFAQ #105](http://mywiki.wooledge.org/BashFAQ/105#Exercises) come to you off the top of your head (should you still *want* to use it, after knowing how unreliable, inconsistent and unintuitive its behavior is in practice). See also https://www.in-ulm.de/~mascheck/various/set-e/, comparing different shells' implementations and how they differ incompatibly from each other. – Charles Duffy Feb 14 '19 at 23:46

1 Answers1

2

Word-Splitting is occurring on your GREP_OPTS="-e \"test this\"" resulting in the command being

grep -e '"test' 'this"'

Resulting in the exact error:

grep: this": No such file or directory

(of course there is no file named "this\"")

See BashFAQ-50 - I'm trying to put a command in a variable, but the complex cases always fail.

In order to prevent word splitting use an array for options instead of trying to use a single variable, e.g.

#!/bin/sh
set -xe

GREP_OPTS=(-e "test this")
echo "I want to test this." | grep "${GREP_OPTS[@]}"

Example Use/Output

$ bash grepopts.sh
+ GREP_OPTS=(-e "test this")
+ echo 'I want to test this.'
+ grep -e 'test this'
I want to test this.

Let me know if you have further questions.

David C. Rankin
  • 81,885
  • 6
  • 58
  • 85