1

I am looking to have 2 variables.

I already have a working setup like follows

var1="$(echo hello)"

When printed like below, it says "hello"

"${var1}" = "hello"

What I would like is

var2=$var1

When printed, displays "echo hello"

"${var2}" = "echo hello"

This may be logically impossible, as var1 is set to be the output of the command, is there anyway I can set var2 to pull the command that sets var1 not the output of the command?

  • 1
    No way. If you call "${var1}" it outputs bash: hello: command not found. Do you mean var1="echo hello"? – Costas Aug 7 '16 at 8:10
1

You cannot pull the command that generated the variable because the information is not there anymore. Yet, you could delay when the command to generate var1 is executed by using eval. For example:

var1="echo hello"
echo "var1: $var1"

var2="$var1"
echo "var2: $var2"

var1=$(eval "$var1")
echo "var1: $var1"

Will print:

var1: echo hello
var2: echo hello
var1: hello

Since you can use eval to execute the command inside var1 until the output of that command is needed you can keep the command itself in var1.

Although this is not a good coding practice. In pretty much all cases it is better to have two variables: once holding the command and one holding the output. Using eval is frowned upon, for several security, and general debugging problems.


On a side note, in this specific case where you have a command where the only shell special characters are whitespace, several shells will allow you to perform the subshell execution from variable without the need for eval, i.e. this will work in most shells:

var3=$($var1)

Works in bash and ksh variants. Doesn't in zsh variants.

  • Scripting is so logical, I love it. Thanks! This will work great. – FreeSoftwareServers Aug 7 '16 at 2:20
  • Yea after implementing it, I went back to the way I had it, which was var & cmd as separate variables. The idea was to make the script easier, but it ended up making the logic more confusing to read and not working well in all cases. Still, Good to know if needed. – FreeSoftwareServers Aug 7 '16 at 2:51
  • 3
    You don't need eval here. var2=$(var1) is enough. – Kusalananda Aug 7 '16 at 6:54
  • @Kusalananda - Correct, but you mean var2=$($var1) right? That's a bash/dash thing as far as i'm aware. Does not work in zsh for example (which would try to resolve $var1 as a command without dropping the quotes first). – grochmal Aug 7 '16 at 13:05
  • @grochmal Yes, I had a typo there. This works in ksh93/pdksh too, which are the shells I'm using. – Kusalananda Aug 7 '16 at 13:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.