Bash 每次while循环时计数器都会重置?
我正在编写一个脚本,如果在5次检查后未找到关联的屏幕,则重新启动进程:Bash 每次while循环时计数器都会重置?,bash,unix,Bash,Unix,我正在编写一个脚本,如果在5次检查后未找到关联的屏幕,则重新启动进程: f=0 while true; do( for s in server1 server2 server3; do( if ! screen -ls|grep -q "$s"; then( f=$(($f + 1)) #Here, f is always 1 more than the value
f=0
while true; do(
for s in server1 server2 server3; do(
if ! screen -ls|grep -q "$s"; then(
f=$(($f + 1))
#Here, f is always 1 more than the value
#I set at the beginning of the script
echo "$s missed $f heartbeats"
)else(
f=0
)fi
if [ "$f" -ge 5 ]; then(
echo "`date`: $s down, starting"
/path/to/start/script
)fi
)done
sleep 1
#f is 0 here
)done
f
在while循环的每次迭代后都被设置回初始值,即使我没有在循环中设置f
。如何使我的计数器持久化?用于将每个循环体和if
语句括起来的不必要的括号形成子shell,对子shell中变量所做的任何更改都是该shell的局部更改,并且在子shell退出时消失
f=0
while true; do
for s in server1 server2 server3; do
if ! screen -ls|grep -q "$s"; then
f=$(($f + 1))
echo "$s missed $f heartbeats"
else
f=0
fi
if [ "$f" -ge 5 ]; then
echo "`date`: $s down, starting"
/path/to/start/script
fi
done
sleep 1
done
从bash
手册页的SHELL语法部分(我的重点):
(list)list在子shell环境中执行(请参见下面的命令执行环境)影响shell环境的变量指定和内置命令在命令执行后不会保持有效
完成。返回状态为列表的退出状态
用于括住每个循环体的不必要的括号和
if
语句构成子shell,对子shell中的变量所做的任何更改都是该shell的局部更改,并在子shell退出时消失
f=0
while true; do
for s in server1 server2 server3; do
if ! screen -ls|grep -q "$s"; then
f=$(($f + 1))
echo "$s missed $f heartbeats"
else
f=0
fi
if [ "$f" -ge 5 ]; then
echo "`date`: $s down, starting"
/path/to/start/script
fi
done
sleep 1
done
从bash
手册页的SHELL语法部分(我的重点):
(list)list在子shell环境中执行(请参见下面的命令执行环境)影响shell环境的变量指定和内置命令在命令执行后不会保持有效
完成。返回状态为列表的退出状态