我想要一个在脚本运行时增加计数的脚本。基本上,当我发现同一国家/地区有 10 台设备出现故障时,我想发送电子邮件通知,并且每次出现故障后都会运行脚本。
因此,如果我将计数器设置为 0,脚本会将值更新为 1,但下次脚本运行时,它会检查计数器是否设置为 0,并再次将值显示为 1。
我需要保存与国家/地区名称相关的先前计数器值,因为这两个值都不固定。还有n
许多设备属于n
多个国家/地区。
答案1
每个国家一个文件/计数器。
#!/bin/bash
#Country name is specified as a comamnd line argument
# ie device_count.sh Brazil
if [[ -z "$1" ]] ; then
echo "Please specify country name" >&2
exit 1
fi
#Create a new file per country if one doesn't exist already
COUNTER_FILE=/var/tmp/devices.$1
if [[ -r $COUNTER_FILE ]] ; then
COUNT=$(<$COUNTER_FILE)
else
COUNT=0
fi
#Increment counter and save to file
echo $(( $COUNT += 1 )) > $COUNTER_FILE
#check if we need to send email
if [[ $(( $COUNT % 10 )) -eq 0 ]] ; then
#We have reached 10 - we need to send an email
echo "BLAH BLAH BLAH " | mailx -s "reached 10" [email protected]
fi
答案2
在退出脚本之前,您需要将国家/地区计数写入文件。下次运行脚本时,您需要从同一文件中读取这些值。否则,您无法将值保留在内存变量中,因为您运行的每个 shell 脚本都会使用自己的变量执行子 shell,并在退出时销毁 shell 和内容。
x="$country"
count=$(cat ${country})
#instead of starting from 0 each time, start from the content of this file
#you need to manually create each country file with value 0 in it
#before start using this struct.
for device_count in $x
do
count=expr $count + 1
echo "Country_[$device_count] count $count"
if [ count -eq 5 ];
then
echo "email to be sent "
fi
done
echo ${count} > ${country}
#at this point you overwrote the file named as
#the name of country you are working here