Var1 is set to contents of command executed, how to set Var2 to be the command from Var1 Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Var1 is set to contents of command executed, how to set Var2 to be the command from Var1 without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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?

Answer

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.

We are here to answer your question about Var1 is set to contents of command executed, how to set Var2 to be the command from Var1 - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji