Bash

如何欺騙初始化腳本返回 0

  • October 14, 2013

我有一個設計不佳的初始化腳本,因為它不符合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

您正在將grep輸出通過管道傳輸到wc並且echo $?將返回wcand not的退出程式碼grep

您可以使用以下-q選項輕鬆規避該問題grep

/etc/init.d/foo status | /bin/grep -q "up and running"; echo $?

如果未找到所需的字元串,grep將返回非零退出程式碼。

編輯:正如mr.spuratic所建議的,你可以說:

/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.)

引用自:https://unix.stackexchange.com/questions/95950