在 Bash 脚本中,如何等到应用程序打开?
例子:
#!/bin/bash
# wait until Thunderbird open to then close its main window...
wmctrl -c "Mozilla Thunderbird"
答案1
基本答案是您必须监视打开的窗口列表以查看是否有变化。您可以通过多种方式执行此操作,但由于您正在使用,因此wmctrl
您可以像这样使用:
#!/bin/bash
while true
do
# get list of windows
windows=$(wmctrl -l)
# check if window is on the list
if [[ "$windows" =~ "Mozilla Firefox" ]];
then
echo "found firefox, closing it in 3 seconds"
sleep 3
wmctrl -c "Mozilla Firefox"
fi
# delay until next loop iteration
sleep 3
done
由于您还要求提供循环示例直到特定窗口关闭,这里有一个经过编辑的示例,采用了替代循环方法(这可能是首选;至少这是我个人经常使用的结构):
#!/bin/bash
# Script enters into this while loop, and keeps checking
# if wmctrl -l lists firefox. Condition is true if firefox
# isn't there. When firefox appears, condition is false,
# loop exits
while ! [[ "$(wmctrl -l)" =~ "Mozilla Firefox" ]]
do
# number of seconds can be changed for better precision
# but shorter time equals more pressure on CPU
sleep 3
done
# Only after firefox appears , we get to here
echo "found firefox, closing it in 3 seconds"
sleep 3
wmctrl -c "Mozilla Firefox"
# Same idea as before - we enter the waiting loop,
# and keep looping until firefox is not on the list
windows=$(wmctrl -l)
while [[ "$(wmctrl -l)" =~ "Mozilla Firefox" ]]
do
sleep 3
done
#When loop exits, that means firefox isn't on the list
echo "Script is done"