Bash – evaluate ENV Variable being stored in a command

Question:

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

[user@smat-jupyterhub-nb-user ~]$ TESTCMD='python script.py'
[user@smat-jupyterhub-nb-user ~]$ SCRIPT=script.py

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

[user@smat-jupyterhub-nb-user ~]$ TESTCMD2='python $SCRIPT'

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

[user@smat-jupyterhub-nb-user ~]$ $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.