Bash – evaluate ENV Variable being stored in a command

Question:

I want to save a command in a variable like this:

[[email protected] ~]$ TESTCMD='python script.py'
[[email protected] ~]$ SCRIPT=script.py

Running $TESTCMD works fine. But I also want to pass a variable to that command:

[[email protected] ~]$ TESTCMD2='python $SCRIPT'

When I run this, I get an error. The Variable does not get evaluated.

[[email protected] ~]$ $TESTCMD2
python: can't open file '/jup/projects/$SCRIPT': [Errno 2] No such file or directory

How can I make this variable being evaluated after being stored in a variable itself?

Asked By: Data Mastery

||

Answers:

That’s because you used ' quotes, instead of " preventing variable substitution.

$ FOO=echo
$ BAR=bar
$ XXX='${FOO} ${BAR}'
$ $XXX
${FOO}: command not found

$ XXX="${FOO} ${BAR}"
$ $XXX
bar

In fact the last one should be rather

$ XXX=""${FOO}" "${BAR}""

with variables additionally quoted in case any of their value contains space.

Answered By: Marcin Orlowski
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.