bash 脚本/pgrep 未按预期工作

标签 bash shell

我有一个 bash 脚本,尝试使用参数调用 pgrep(过度简化):

PATTERN="'/opt/apps/bin/lighttpd.bin -f /opt/apps/etc/lighttpd/lighttpd.conf\$'"
pgrep -f $PATTERN
echo pgrep -f $PATTERN

给出以下输出:

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$'

我想这意味着参数没有传递给 pgrep,而是由于某种原因传递给了 echo。

我的期望:

7632
pgrep -f '/opt/apps/bin/lighttpd.bin -f /opt/apps/etc/lighttpd/lighttpd.conf$'

当我单独运行 preg 行时,它按预期输出 7632。

我在这里做错了什么吗?我尝试过 sh、dash 和 bash。同样的结果,我真的没有看到问题。

最佳答案

您需要将 PATTERN 用双引号引起来:

PATTERN="/opt/apps/bin/lighttpd.bin -f /opt/apps/etc/lighttpd/lighttpd.conf\$"
pgrep -f "$PATTERN"

参见:quoting variables

编辑:并且为了回显我会这样做:

echo pgrep -f \'$PATTERN\'

关于bash 脚本/pgrep 未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9364676/

相关文章:

mongodb - 如何克隆(重复)同一数据库集合中的 MongoDB 对象?

c - 使用 tee 连续输出 C 程序

arrays - 命令的多行输出未按预期将元素分配给 bash 数组

bash - 电子邮件警报和 ping 脚本

linux - crontab中运行脚本--reboot : command not found

bash - shell glob 扩展如何像 ls -l * 一样工作?

bash - crontab 和手动运行脚本之间的不同结果

bash shell 程序

shell - 简单的 shell 脚本可以在 cygwin 中运行,但不能在 solaris 上运行

bash - 在 shell 脚本中定义一个 Increment 变量,该变量在每个 cronjob 上递增