Home > Back-end >  Why can't you execute a bash command with temporary env variable assignment?
Why can't you execute a bash command with temporary env variable assignment?

Time:10-22

More concisely in code -- why does this work:

X=5 eval "echo \$X"

outputs: 5

But not this:

substitute_cmd='X=5 eval "echo \$X"'
$substitute_cmd

outputs: -bash: X=5: command not found

& Are there any good workarounds for it?

CodePudding user response:

  • eval: it has a built-in interprets, which means it behaves as the same way when you type the command in the shell.
  • $cmd: it will expand the variable, and literally treats the cmd here as a executable command

Here, X=5 is not a executable command, it needs a shell to interprets it, so eval ok for you, while $cmd not ok for you. You still need another eval outside to help you like next:

$ substitute_cmd='X=5 eval "echo \$X"'
$ eval $substitute_cmd
5
  •  Tags:  
  • bash
  • Related