Maciej Maciej - 6 months ago 12
Bash Question

Interpreting shell variables in bracket grep

I have command like this :

grep ABC /tmp/dir{1,3,7}/file*.txt


It works perfectly fine, but I need extract constant with filename like this:

FILENAME="/tmp/dir{1,3,7}/file*.txt"
grep ABC $FILENAME


This does not work due the braces.
How can I do it ?

Answer

This is one case in which eval may be useful -and hopefully safe:

eval grep ABC "$FILENAME"

Test

$ seq 10 > a1
$ seq 10 > a2
$ seq 10 > a3
$ grep 5 a{1..3}
a1:5
a2:5
a3:5

But if we store in a variable it gets literal...

$ f=a{1..3}
$ echo $f
a{1..3}
$ echo "$f"
a{1..3}
$ grep 5 "$f"
grep: a{1..3}: No such file or directory

Hence the usage of eval:

$ eval echo "$f"
a1 a2 a3
$ eval grep 5 "$f"
a1:5
a2:5
a3:5