1

シェル (bash) スクリプトで使用するカウンターを作成する必要があります。スクリプトが呼び出されるたびに、含まれる数値を 1 ずつ増やす必要があり、その数値は 6 桁の数値として保持する必要があるため、初期値は 000000 になります。次に 000001、次に 000002 など... 私がやっていることは、最初の行に 6 桁の整数を含む「counter」という名前のファイルを作成することです。スクリプトから私はこのコードを持っています:

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

問題は、2 番目のステップで機能しないことです。おそらく最初のステップが実際に失敗している可能性があります。アドバイスはありますか?

オプションは次のとおりです。

#!/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

[更新:テキストファイルに明示的なベースマーカーを含めるように修正されましたが、GlennJackmanが私を打ち負かしました。]

これを少し単純化できます。

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 に答える
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 に答える
0

で解決

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