如何在变量中执行字符串命令?

时间:2014-11-21 10:32:48

标签: linux bash

说我有一个变量:

T=6

另一个名为'line'的变量,我从文件中读取并包含以下字符串/文本:

echo "$T"

现在我想执行'line'中写的命令,所以我会得到:

6

就像我只会输入命令一样:

echo "$T"

得到:

6

我试图使用:

$line

但我得到了:

"$T"

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

eval正是您要找的

例如考虑

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

从手册页

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.