bash 脚本/pgrep 没有按预期工作
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9364676/
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
bash script/pgrep not working as expected
提问by alex
I have a bash script that tries to call pgrep with arguments (Over simplified):
我有一个 bash 脚本,它尝试使用参数调用 pgrep(过度简化):
PATTERN="'/opt/apps/bin/lighttpd.bin -f /opt/apps/etc/lighttpd/lighttpd.conf$'"
pgrep -f $PATTERN
echo pgrep -f $PATTERN
Gives the following output:
给出以下输出:
Usage: pgrep [-cflvx] [-d DELIM] [-n|-o] [-P PPIDLIST] [-g PGRPLIST] [-s SIDLIST]
[-u EUIDLIST] [-U UIDLIST] [-G GIDLIST] [-t TERMLIST] [PATTERN]
pgrep -f '/opt/apps/bin/lighttpd.bin -f /opt/apps/etc/lighttpd/lighttpd.conf$'
I suppose it means the argument is not passed to pgrep but is passed to echo for some reason.
我想这意味着参数没有传递给 pgrep 而是由于某种原因传递给 echo 。
What I'm expecting:
我期待的是:
7632
pgrep -f '/opt/apps/bin/lighttpd.bin -f /opt/apps/etc/lighttpd/lighttpd.conf$'
When I run the preg line by itself, it outputs 7632 as expected.
当我单独运行 preg 行时,它按预期输出 7632。
Am I doing something wrong here? I've tried with sh, dash and bash. Same outcomes, I really don't see the problem.
我在这里做错了吗?我试过 sh、dash 和 bash。同样的结果,我真的没有看到问题。
回答by barti_ddu
You need to surround PATTERNin double quotes:
您需要用双引号将PATTERN括起来:
PATTERN="/opt/apps/bin/lighttpd.bin -f /opt/apps/etc/lighttpd/lighttpd.conf$"
pgrep -f "$PATTERN"
See: quoting variables
请参阅:引用变量
Edit:and for echoing i would just do:
编辑:为了回声,我会这样做:
echo pgrep -f \'$PATTERN\'
回答by shellter
As I don't have lighttpd.bin available to test with, I am submitting an untested option, mostly agreeing with @barti_ddu, but with a slightly different twist
由于我没有可以测试的 lighttpd.bin,我提交了一个未经测试的选项,主要同意@barti_ddu,但略有不同
PATTERN='/opt/apps/bin/lighttpd.bin -f /opt/apps/etc/lighttpd/lighttpd.conf$'
pgrep -f "$PATTERN"
echo pgrep -f "$PATTERN"
I would keep the single quotes on the assingment to PATTERN, but totally agree you need the dbl-quoting when using with pgrep or echo.
我会在对 PATTERN 的赋值中保留单引号,但完全同意在与 pgrep 或 echo 一起使用时需要 dbl 引用。
I hope this helps.
我希望这有帮助。

