我有一個設計不良的初始化腳本,因為它不符合Linux 標準基本規範
如果正在運行,以下命令的退出代碼應為 0,如果未運行,則退出代碼應為 3
service foo status; echo $?
然而,由於腳本的設計方式,它總是返回 0。
如何解決該問題,以便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.)