Bash:执行包括管道在内的变量内容

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48098218/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 16:43:55  来源:igfitidea点击:

Bash: execute content of variable including pipe

bash

提问by chris01

#!/bin/bash

# 1st part
ret=$(ps aux | grep -v grep)    # thats OK 
echo $ret

# 2nd part
cmd="ps aux | grep -v grep"     # a problem with the pipe | 
ret=$($cmd)         
echo $ret

How can I use a command-string as I have in the 2nd part? Think the pipe is the problem. Tried to escape it but it did not help. Get some snytax error of ps.

如何使用第二部分中的命令字符串?认为管道有问题。试图逃脱它,但它没有帮助。得到一些 ps 的 snytax 错误。

Thanks!

谢谢!

采纳答案by Inian

Using evalis not recommended here. It can lead to unexpected results, especially when variables can be read from untrusted sources (See BashFAQ/048 - Eval command and security issues.

eval这里不推荐使用。它可能会导致意外结果,尤其是当可以从不受信任的来源读取变量时(请参阅BashFAQ/048 - Eval 命令和安全问题

You can solve this in a simple way by defining and calling a function as below

您可以通过如下定义和调用函数来以简单的方式解决此问题

ps_cmd() {
    ps aux | grep -v grep
}

and use it in the script as

并在脚本中使用它作为

output="$(ps_cmd)"
echo "$output"

Also a good read would be to see why storing commands in a variable is not a good idea and has a lot of potential pitfalls - BashFAQ/050 - I'm trying to put a command in a variable, but the complex cases always fail!

另外一个很好的阅读是了解为什么将命令存储在变量中不是一个好主意,并且有很多潜在的陷阱 - BashFAQ/050 - 我试图将命令放入变量中,但复杂的情况总是失败!

回答by Hyman

You need eval:

你需要eval

ret=$(eval "$cmd")