使用“手表"在Bash中重复运行功能? [英] Using "watch" to run a function repeatedly in Bash?
问题描述
这是我的第一个Bash脚本.我的Debian机器出现WiFi问题.我不是要问起因,而是要对Bash的问题进行创可贴.我的WiFi会随机消失,通常每12-15分钟消失一次.我在此服务器上使用SSH,不需要从物理服务器手动运行 ifdown wlan0
和 ifup wlan0
(重新连接WiFi).
This is my first Bash script. I have a WiFi issue with my Debian machine. I'm not here to ask about the cause, but rather how to put a band-aid on the issue with Bash. My WiFi will drop out at a random time, usually every 12-15 minutes. I use SSH on this server, and do not want to have to run ifdown wlan0
and ifup wlan0
(which reconnects the WiFi) manually from the physical server.
此Bash脚本的功能是尝试连接3次.如果失败三次,它将放弃.否则,每三秒钟它将通过尝试ping Google来检查我的服务器是否已连接.
The function of this Bash script is to attempt to connect three times. If it fails three times, it will give up. Otherwise, every three seconds it will check whether or not my server is connected by attempting to ping Google.
#!/bin/bash
ATTEMPTS=1
function test_connection {
ping -c 1 www.google.com
local EXIT_CODE=$?
if [ $EXIT_CODE -eq 0 ]
then
return true
else
return false
fi
}
function reset_connection {
ifdown wlan0
ifup wlan0
EXIT_CODE=$((EXIT_CODE+1))
}
function connection_test_loop {
if [ $ATTEMPTS -ge 3 ]
then
echo CONNECTION FAILED TO INITIALIZE ... ATTEMPT $ATTEMPTS FAILED ... EXITING
exit
fi
if ! [ test_connection ]
then
echo CONNECTION DROPPED ... ATTEMPTING TO RE-ESTABLISH CONNECTION ... ATTEMPT $ATTEMPTS
reset_connection
fi
}
test_connection
if [ $? ]
then
echo CONNECTION PRE-ESTABLISHED
watch -n 3 connection_test_loop
else
echo CONNECTION FAILED TO INITIALIZE ... ATTEMPTING TO RESET CONNECTION ... ATTEMPT $ATTEMPTS
reset_connection
if [ $? ]
then
echo CONNECTION ESTABLISHED
watch -n 3 connection_test_loop
else
echo CONNECTION FAILED TO INITIALIZE ... ATTEMPT $ATTEMPTS FAILED ... EXITING
exit
fi
fi
我已经隔离了此脚本存在的问题.它在于使用 watch
调用 connection_test_loop
函数.我一直无法找到任何有关为什么它无法按预期执行并每三秒钟运行一次功能的信息.
I've isolated the issue I'm having with this script. It lies in calling the connection_test_loop
function with watch
. I've been unable to find any information as to why this isn't performing as expected and running the function every three seconds.
推荐答案
watch
可能不知道您的connection_test_loop函数.您可以尝试在下面添加 export
test_connection也许可以解决问题:
It's possible that watch
is not aware of your connection_test_loop function. You can try adding an export
below the test_connection to perhaps solve the issue:
test_connection
export -f connection_test_loop
...
↳ http://linuxcommand.org/lc3_man_pages/exporth.html
调用 watch
时,您可能需要以下语法:
When calling watch
, you may need this syntax:
watch -x bash -c connection_test_loop
这篇关于使用“手表"在Bash中重复运行功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!