我如何检查进程是否正在运行,如果它正在运行,那么echo"进程正在运行"并防止他们使用该过程直到完成。我有这段代码,但我不能让它在回声之后不允许它们使用该过程:
#!/bin/bash
SERVICE=EXAMPLE
if ps ax | grep -v grep | grep -v grep | grep $SERVICE > /dev/null
then
echo -e ""
echo -e "${LIGHTRED}[!] ${WHITE}Please wait till process is finished."
fi
答案 0 :(得分:1)
似乎你想写一个循环,而不是一个if
语句。
你可能想在检查条件之间睡一会儿。
#!/bin/bash
SERVICE=EXAMPLE
while ps ax | grep -v grep | grep "$SERVICE" > /dev/null
do
echo
echo -e "${LIGHTRED}[!] ${WHITE}Please wait till process is finished."
sleep 60
fi
如果你有pgrep
:
while pgrep "$SERVICE" >/dev/null
(如果while pgrep -q "$SERVICE"
的实施支持,则更简单pgrep
。)
当没有匹配的过程(已经完成或尚未开始)时, 那么脚本不会产生任何输出。 如果你想在这种情况下得到一些输出, 然后你可以像这样重做:
while true
do
if pgrep "$SERVICE" > /dev/null; then
echo
echo -e "${LIGHTRED}[!] ${WHITE}Please wait till process is finished."
sleep 60
else
echo "Process '$SERVICE' not running"
break
fi
fi
仅打印消息一次,并等待该过程不再运行:
is_running() {
pgrep "$SERVICE" > /dev/null
}
if is_running; then
echo -e "${LIGHTRED}[!] ${WHITE}Please wait till process is finished."
while true; do
sleep 60
is_running || break
done
else
echo "Process '$SERVICE' not running"
fi
答案 1 :(得分:0)
另一种解决方案
#!/bin/bash
tput civis # hide cursor
until ! ps -ef | grep "$SERVICE" | grep -v "grep" > /dev/null; do
while ps -ef | grep "$SERVICE" | grep -v "grep" > /dev/null; do
echo -en "\r${LIGHTRED}[!] ${WHITE}Please wait till process is finished."
done
printf "\r%80s" "" # clear line
echo -en "\rProcess '$SERVICE' is completed!\n"
done
tput cnorm # show cursor again
如果您同时拥有多个服务实例,此解决方案也很有用。