我制作了一个简单的脚本来重新启动我的路由器,然后显示一个进度条,直到我的电脑再次连接到互联网。
运行脚本时,我得到以下输出:
The router is now rebooting...
############################################bin/reboot_router: line 48: 4758 Alarm clock: 14 ping -Q -c 1 -t 1 google.com >&/dev/null
#bin/reboot_router: line 48: 4761 Alarm clock: 14 ping -Q -c 1 -t 1 google.com >&/dev/null
#bin/reboot_router: line 48: 4763 Alarm clock: 14 ping -Q -c 1 -t 1 google.com >&/dev/null
#####bin/reboot_router: line 48: 4773 Alarm clock: 14 ping -Q -c 1 -t 1 google.com >&/dev/null
#bin/reboot_router: line 48: 4775 Alarm clock: 14 ping -Q -c 1 -t 1 google.com >&/dev/null
##bin/reboot_router: line 48: 4777 Alarm clock: 14 ping -Q -c 1 -t 1 google.com >&/dev/null
#
Run Code Online (Sandbox Code Playgroud)
我想抑制Alarm clock: 14
出现的东西,所以输出变成:
The router is now rebooting...
#######################################################
Run Code Online (Sandbox Code Playgroud)
脚本的相关部分是:
#!/bin/bash
COLUMNS=$(tput cols)
# Reboot router code here
echo 'The router is now rebooting...'
min_time=60
max_time=120
start_time=$SECONDS
time=0
progress=0
until [[ $min_time -lt $time ]] && ping -Q -c 1 -t 1 google.com &> /dev/null; do
let time=SECONDS-start_time
let new_progress=COLUMNS*time/max_time
let diff=new_progress-progress
let progress=new_progress
for((i=0; i<diff; i++)); do
echo -n '#'
done
sleep 1
done
echo
Run Code Online (Sandbox Code Playgroud)
您的问题是您的 ping 命令包含-t 1
告诉 ping 在 1 秒后放弃。这会导致SIGALRM
ping 无法在内部捕获的信号。(这可以说是一个 ping 错误,但这是学术性的)。bash shell 将此报告为Alarm clock: 14
并中止进程,退出状态为142
; 128(即“我捕获到信号”标志)+ 14(SIGALRM id)。
有两种方法可以解决这个问题:
1) 删除-t 1
以便不生成 SIGALRM。相反,ping 将在(根据我的经验)5 秒后超时,并给出与您当前看到的不同的错误状态;如果无法访问指定的主机,则可能为 68。在这种情况下,您可能还想将“-o”添加到您的 ping 中,以便它在主机可访问时立即终止。
2)trap - SIGALRM
在 ping 命令之前执行,告诉 shell 忽略信号。1 秒超时仍然会发生,退出状态仍然是142
。至少,这是我在运行 Yosemite (10.10.5) 的 iMac 上所做的尝试。