bash:执行存储在变量中的命令 [英] bash: executing command stored in variable

查看:44
本文介绍了bash:执行存储在变量中的命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写脚本,但其中一部分无法正常运行.为了简单起见,我在一个简单的示例中对此部分进行了细分

I am writing a script, and one part of it is not working as I would expect. I have broken out this part in a simple example for simplicity

echo 'echo "" > tmp' | while read cmd; do  $cmd ; done

在这里,我希望完整的命令"echo"> tmp"由$ cmd执行.但是发生了什么

Here I would expect the full command, "echo "" > tmp" to be executed by $cmd. But what happens is this

"" > tmp

执行的命令在字面上回显"> tmp.而不是回显"并将其重定向到文件tmp.将命令存储在$ cmd中,然后稍后尝试执行该命令时,显然出了点问题.

The command executed echoes out "" > tmp literaly. Instead of echoing out "" and redirecting it to the file tmp. Obviously something is wrong when storing the command in $cmd and then later trying to execute it.

即使我进一步简化它,结果也是一样

The result is the same even if I simplify it further

cmd="echo "" > tmp"
$cmd
> tmp

我尝试尝试使用''和"的不同用法,但尚未解决.

I have tried to experiment with different usages of '' and "" but not solved it yet.

推荐答案

使用 eval 执行存储在变量中的命令:

Use eval to execute the command stored in variable:

echo 'echo "" > tmp' | while read cmd; do eval "$cmd" ; done

cmd 的值将为 echo">tmp .然后,当Bash将参数替换解析为命令时,部分">tmp 将是 echo 的字符串参数,不会被识别为> (重定向).因此,它将仅输出参数部分.

The value of cmd will be echo "" > tmp. Then when Bash resolves the parameter substitution as a command, the part "" > tmp will be the string arguments of echo, not be recognized as >(redirection). So it will just output the arguments part.

与以下内容相同: $(echo'echo"> tmp')

这篇关于bash:执行存储在变量中的命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆