本文介绍了Bash:执行变量内容,包括管道的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#!/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

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

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.

谢谢!

推荐答案

此处不建议使用eval.它可能导致意外结果,尤其是当可以从不受信任的来源读取变量时(请参见 BashFAQ/048-Eval命令和安全问题.

Using eval is 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.

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

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

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

并在脚本中将其用作

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

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

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!

这篇关于Bash:执行变量内容,包括管道的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 11:07