1

我需要创建一个计数器以在 shell(bash)脚本中使用,每次调用脚本时,包含的数字必须增加一,并且数字应保持为六位数字,因此初始值为 000000,然后是 000001,然后是 000002 等等.....我正在做的是,我创建了一个名为“counter”的文件,该文件在第一行包含一个 6 位整数。所以从脚本我有这个代码:

index= cat /path/counter | tail -1   #get the counter
tmp=`expr $index + 1`                #clone and increase the counter
echo "" >/path/counter               #empty the counter
echo ${tmp} >/path/counter           #insert clone

问题是它在第二步不起作用,可能是第一步实际上失败了,你有什么建议吗?

一个选项如下:

#!/bin/bash

read index < /path/counter
declare -i tmp=index+1
printf "%06d" $tmp > /path/counter

问题是它只将文件的内容提升到 000007,之后我得到:

-bash: 000008: value too great for base (error token is "000008")

有什么建议吗?

4

5 回答 5

3

您没有正确阅读索引。尝试:

index=$(tail -1 /path/counter)

其他需要注意的事项:

  • 你不需要cattail可以自己处理
  • 您可以将反引号替换为tmp=$(expr ...)
  • 您不需要echo "">重定向会截断文件

编辑

要使数字宽为 6 位,请尝试printf代替echo

printf "%06d", $index
于 2012-09-07T11:41:26.790 回答
2

bash 有一种机制,您可以在其中指定数字的基数

#!/bin/bash
file=/path/to/counter
[[ ! -f "$file" ]] && echo 0 > $file              # create if not exist
index=$(< "$file")                                # read the contents
printf "%06d\n" "$((10#$index + 1))" > "$file"    # increment and write
于 2012-09-07T14:36:30.053 回答
1

这也可以:

#!/bin/bash

if [ -e /tmp/counter ]
  then
    . /tmp/counter
  fi

if [ -z "${COUNTER}" ]
  then
    COUNTER=1
  else
    COUNTER=$((COUNTER+1))
  fi

echo "COUNTER=${COUNTER}" > /tmp/counter

echo ${COUNTER}
于 2012-09-07T11:47:42.467 回答
1

[更新:修复在文本文件中包含一个明确的基本标记,但格伦杰克曼击败了我。]

您可以稍微简化一下:

read index < /path/counter   # Read the first line using bash's builtin read
declare -i tmp=index+1       # Set the integer attribute on tmp to simplify the math
printf "10#%06d" $tmp > /path/counter    # No need to explicitly empty the counter; > overwrites

或者,您甚至不需要临时变量来保存增量值:

read index < /path/counter
printf "10#%06d" $(( index+1 )) > /path/counter
于 2012-09-07T12:21:09.537 回答
0

解决了

index=$(cat /path/counter| tail -1)
tmp=$(expr $index + 1)
printf "%06d" $tmp > /path/counter
于 2012-09-07T14:57:00.667 回答