user3206874
user3206874

Reputation: 977

How to execute string command in a variable?

Say I have a variable:

T=6

And another variable called 'line' that I read from a file and that contains the following string/text:

echo "$T"

Now I want to execute the command written in 'line' so I'll get:

6

Just like what I will get if will just type the command:

echo "$T"

And get:

6

I tried to use:

$line

But I got:

"$T"

Thanks in advance for the help.

Upvotes: 3

Views: 218

Answers (1)

nu11p01n73R
nu11p01n73R

Reputation: 26667

eval is what you are looking for

For example consider

$ T=6
$ line='echo "$T"'
$ eval $line
6

From man pages

eval [arg ...]
              The  args  are  read  and concatenated together into a single command.  This command is then read and executed by the shell, and its exit
              status is returned as the value of eval.  If there are no args, or only null arguments, eval returns 0.

Upvotes: 2

Related Questions