[英]Wait until service starts in bash-script
我有一個 bash 腳本,它在后台啟動一些服務。 此服務成功啟動后,它會將“服務器處於活動狀態”打印到標准輸出。 我需要等到這個字符串出現,然后繼續執行我的腳本。 我怎樣才能做到這一點?
我會這樣做。
./server > /tmp/server-log.txt &
sleep 1
while ! grep -m1 'Server is active' < /tmp/server-log.txt; do
sleep 1
done
echo Continue
這里-m1
告訴grep(1)
在第一場比賽時退出。
我用下面的玩具“服務”很好地回答了我的答案:
#! /bin/bash
trap "echo 'YOU killed me with SIGPIPE!' 1>&2 " SIGPIPE
rm -f /tmp/server-output.txt
for (( i=0; i<5; ++i )); do
echo "i==$i"
sleep 1;
done
echo "Server is active"
for (( ; i<10; ++i )); do
echo "i==$i"
sleep 1;
done
echo "Server is shutting down..." > /tmp/server-output.txt
如果你用echo Continue
替換echo Continue; sleep 1; ls /tmp/server-msg.txt
echo Continue; sleep 1; ls /tmp/server-msg.txt
echo Continue; sleep 1; ls /tmp/server-msg.txt
,你會看到ls: cannot access /tmp/server-output.txt: No such file or directory
證明“Continue”動作在Server is active
的輸出Server is active
后被觸發。
使用grep -q
。 -q
選項使grep
安靜,當文本出現時它會立即退出。
下面的命令在后台啟動./some-service
,並阻塞直到“服務器處於活動狀態”出現在標准輸出上。
(./some-service &) | grep -q "Server is active"
讓我閱讀service
應用程序的服務狀態:
$ /sbin/service network status
network.service - Network Connectivity
Loaded: loaded (/lib/systemd/system/network.service; enabled)
Active: active (exited) since Ср 2014-01-29 22:00:06 MSK; 1 day 15h ago
Process: 15491 ExecStart=/etc/rc.d/init.d/network start (code=exited, status=0/SUCCESS)
$ /sbin/service httpd status
httpd.service - SYSV: Apache is a World Wide Web server. It is used to serve HTML files and CGI.
Loaded: loaded (/etc/rc.d/init.d/httpd)
Active: activating (start) since Пт 2014-01-31 13:59:06 MSK; 930ms ago
它可以通過代碼完成:
function is_in_activation {
activation=$(/sbin/service "$1" status | grep "Active: activation" )
if [ -z "$activation" ]; then
true;
else
false;
fi
return $?;
}
while is_in_activation network ; do true; done
您是否要求將 stderr 重定向到 stdout?
./yourscript.sh 2>&1 |grep "Server is active" && echo "continue executing my script"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.