I need to create a counter to use in a shell (bash) script, each time the script is called
the number contained has to be increased by one and the number should be kept as six digit number, so the initial value would be 000000, then 000001, then 000002 and so on…..
What i’m doing is, i create a file named ‘counter’ which contains a 6 digits integer on the first line.
so from the script i have this code:
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
The problem is that its not working at the second step, probably is the first step which is actually failing, do you have an advice?
An option would be the following :
#!/bin/bash
read index < /path/counter
declare -i tmp=index+1
printf "%06d" $tmp > /path/counter
The problem is that it raises the content of the file only until 000007, after that i get:
-bash: 000008: value too great for base (error token is "000008")
Any Advice?
[UPDATE: fixed to include an explicit base marker in the text file, but Glenn Jackman beat me to it.]
You can simplify this a bit:
Or, you don’t even need a temporary variable to hold the incremented value: