4

I have an environment variable called $TEST which refers to a directory in my bash script I have a variable called $VARTEST which is $TEST/dir/file

now I want to grep the file specified by $VARTEST so I try to do:
grep somestring $VARTEST but it doesn't translate $TEST into it's directory

I've tried different combinations of {}, "" and '' but without success

2 Answers 2

6

I think you want

eval grep somestring "$VARTEST"

or even

VARTEST_EVALUATED=$(eval echo $VARTEST)
grep "$SOMESTRING" "$VARTEST_EVALUATED"

but remember (as others already said): If possible use

VARTEST="$TEST/foo/bar"

instead of

VARTEST='$TEST/foo/bar'

use the second one only if you really need kind of 'lazy evaluation'...

Warning, this could be dangerous if $VARTEST contains malicous code.

Sign up to request clarification or add additional context in comments.

2 Comments

that did the trick, however a new problem surfaced, somestring in my case is a variable which contains a whitespace $SOMESTRING = "some thing" now grep searches for some and uses thing as a filename, ie the ""'s are lost
Ugly, but use eval grep "\"$SOMESTRING\"" "$VARTEST"
1

Have you put single quotes around something? Single quotes will prevent the variables from being translated into their corresponding values. Double quotes will work though. For example:

#!/bin/sh

TEST="/etc"
VARTEST="$TEST/passwd"
grep "$LOGNAME" "$VARTEST"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.