如何添加变量来计算脚本被调用的次数?

时间:2014-06-19 08:36:09

标签: shell

我正在编写一个脚本,用于在脚本运行后将数据添加到文件中。 由于我需要向前邮寄数据,我需要一个变量来分配脚本被调用的次数。

我正在使用存储count值的临时文件。每次调用脚本时,都会调用变量temp,该值会递增并存储在count中。增量值将存储回温度。

count=$((temp + 1))
echo $count > temp
printf "%d\t%10s\t" "$count" "$datet" >> table

这是我正在使用的代码,但是temp并没有增加......?

2 个答案:

答案 0 :(得分:2)

只需先阅读之前的值:

temp=$(cat temp)
count=$((temp + 1))
echo "$count" > temp
printf "%d\t%10s\t" "$count" "$datet" >> table

测试

$ echo "0" > temp
$ ./a
$ cat temp 
1
$ ./a
$ cat temp 
2

答案 1 :(得分:1)

您必须使用cat temp获取文件temp中的值。

但我建议为临时文件使用一个变量以获得更好的代码可重用性:

TMP=/tmp/counter
if [ ! -f $TMP ]; then echo "0">$TMP; fi
count=$(($(cat $TMP) + 1))
echo $count > $TMP
printf "%d\t%10s\t" "$count" >> /tmp/somelogfile

或者在一行中,如果您不需要变量中的计数:

echo "$(($(cat $TMP) + 1))">$TMP

然后您可以稍后使用:

echo $(cat $TMP)
相关问题