Home > Net >  Bash - evaluate ENV Variable being stored in a command
Bash - evaluate ENV Variable being stored in a command

Time:11-26

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?

CodePudding user response:

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.

  • Related