如何欺骗初始化脚本返回 0

spu*_*der 4 grep bash init-script exit init

我有一个设计不佳的初始化脚本,因为它不符合Linux 标准基本规范

如果正在运行,则以下代码的退出代码应为 0,如果未运行,则退出代码应为 3

service foo status; echo $? 
Run Code Online (Sandbox Code Playgroud)

然而,由于脚本的设计方式,它总是返回 0。我无法在没有重大重写的情况下修复脚本(因为 service foo restart 依赖于 service 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
Run Code Online (Sandbox Code Playgroud)

dev*_*ull 5

您正在通过管道将grep输出发送到wc并且echo $?将返回wc和 not的退出代码grep

您可以使用以下-q选项轻松规避该问题grep

/etc/init.d/foo status | /bin/grep -q "up and running"; echo $?
Run Code Online (Sandbox Code Playgroud)

如果未找到所需的字符串,grep将返回一个非零退出代码。

编辑:正如mr.spuratic所建议的,你可以说:

/etc/init.d/foo status | /bin/grep -q "up and running" || (exit 3); echo $?
Run Code Online (Sandbox Code Playgroud)

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.)
Run Code Online (Sandbox Code Playgroud)


归档时间:

查看次数:

2617 次

最近记录:

11 年,11 月 前