我正在寻找一种带有 while 循环的替代方法,它应该从一个文件中检索输入。即使我未能在 while true 条件下解释这一点,在这种情况下我也无法从文件中提供变量,例如 (cat filename
),
我的要求是每 5 分钟通过 ping 测试检查 100 台服务器是否启动,并将其记录到某个自定义位置(假设 /tmp/output/out-`date +%F`
)。同样的脚本应该在 7 天后删除相同的日志,并且每个文件大小的最大大小不超过 1MB。
while read IP
do
ping -c1 $IP &> /dev/null && echo $IP is up || echo $IP is down
sleep 2
done < IP
注意:要在无限循环中运行此脚本,我无法将输入解析为文件中的变量。
while true
do
...
done < filename
想法赞赏 :)
最佳答案
多个任务并行运行:
#!/bin/bash
t=5m # time interval
p=() # pid list
_pingAndLog(){ # $1 is the server ip list
local ip
while :; do
while read -r ip || [[ -n $ip ]]; do
if ping -c1 $ip >/dev/null 2>&1; then
echo "`date +%H:%M`: $ip is up"
else
echo "`date +%H:%M`: $ip is down"
fi >>pingtest-`date +%F`.log
done <"$1" # $1 = ip list
sleep "$t"
done
}
_killOldLog(){
while :; do
# use "-mtime +7" to find old files, 7 days
find . -type f -mtime +7 -name 'pingtest-*\.log' -delete
sleep 24h
done
}
_cleanUp(){
echo kill ${p[@]}
kill ${p[@]}
}
for s in *\.list; do # for each file ip list
[[ "$s" = '*.list' ]] && break # no file found, then quit
_pingAndLog "$s" & p+=($!) # run in background, remember pid
done
_killOldLog & p+=($!)
trap _cleanUp 0 2 3 # 0-exit; 2-interrupt, 3-quit
wait # wait backround jobs; Ctrl-C to exit
注意:
- 因为日志文件是按日期分隔的,所以可能不需要检查它们的大小;只需删除那些旧的。
while sleep "$t"; do .. done
也可以根据需要构造无限循环。- 我修改了这个脚本,以便它可以并行 ping 多个 IP 列表。
关于linux - 真正从 Bash 中的列表中获取输入时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48383870/