我有一个设计不佳的初始化脚本,因为它不符合Linux 标准基本规范
如果正在运行,以下命令的退出代码应为 0,如果未运行,则退出代码应为 3
service foo status; echo $?
然而,由于脚本的设计方式,它总是返回 0。如果不进行重大重写,我无法修复脚本(因为服务 foo 重新启动取决于服务 foo 状态)。
如何解决该问题,以便service foo status
在运行时返回 0,在未运行时返回 3?
到目前为止我所拥有的:
root@foo:/vagrant# service foo start
root@foo:/vagrant# /etc/init.d/foo status | /bin/grep "up and running"|wc -l
1
root@foo:/vagrant# /etc/init.d/foo status | /bin/grep "up and running"|wc -l;echo $?
0 # <looks good so far
root@foo:/vagrant# service foo stop
root@foo:/vagrant# /etc/init.d/foo status | /bin/grep "up and running"|wc -l
0
root@foo:/vagrant# /etc/init.d/foo status | /bin/grep "up and running"|wc -l;echo $?
0 # <I need this to be a 3, not a 0
答案1
您将grep
输出通过管道传输到wc
and将返回and not 的echo $?
退出代码。wc
grep
您可以使用以下-q
选项轻松规避该问题grep
:
/etc/init.d/foo status | /bin/grep -q "up and running"; echo $?
如果未找到所需的字符串,grep
将返回一个非零退出代码。
编辑:按照建议斯普拉蒂克先生,你可以说:
/etc/init.d/foo status | /bin/grep -q "up and running" || (exit 3); echo $?
3
如果未找到字符串,则返回退出代码。
man grep
会告诉:
-q, --quiet, --silent
Quiet; do not write anything to standard output. Exit
immediately with zero status if any match is found, even if an
error was detected. Also see the -s or --no-messages option.
(-q is specified by POSIX.)