简体   繁体   English

如何将命令的一部分作为变量bash传递?

[英]How to pass parts of a command as variable bash?

a="grep ssh | grep -v grep"
ps -ef | $a | awk '{print $2}'

How can I make the above work? 我怎样才能完成上述工作? I have a section where I need to not just pass the grep term, but possible pass more than one grep term, meaning I need to pass "term1 | grep term2" as a variable. 我有一个部分,我不仅要传递grep术语,但可能传递多个grep术语,这意味着我需要将“term1 | grep term2”作为变量传递。

Edit: 编辑:

another.anon.coward answer below worked perfectly for me. 另一个。下面的回答对我来说非常合适。 Thank you sir! 谢谢你,先生!

Create a function instead: 改为创建一个函数:

a() {
    grep ssh | grep -v grep
}
ps -ef | a | awk '{print $2}'

The other solution is to use eval but it's unsafe unless properly sanitized, and is not recommended. 另一种解决方案是使用eval,但除非经过适当的消毒,否则不安全,不建议使用。

a="grep ssh | grep -v grep"
ps -ef | eval "$a" | awk '{print $2}'

If you want just the pid of a process, then use pgrep . 如果你只想要一个进程的pid ,那么使用pgrep

pgrep ssh

You can put this in a bash like the following (a.bash) : 您可以将其放在bash中,如下所示(a.bash):

#!/bin/bash
pname=$1
pgrep "$pname"

or if you want ps -ef for other purposes as you've written, following inside a script might work: 或者如果您希望将ps -ef用于其他目的,则可以在脚本内部执行以下操作:

pname=$1
ps -ef | grep "$pname" | grep -v grep | awk '{print $2}'  # I would personally prefer this

OR 要么

ps -ef | eval "$pname" | awk '{print $2}'  # here $pname can be "grep ssh | grep -v grep"

change the permission to execute : 更改要执行的权限:

chmod a+x a.bash
./a.bash ssh

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM