Home > Software design >  BASH count with two digit even its a one digit task
BASH count with two digit even its a one digit task

Time:01-26

i'am currently trying to count 1 to a variable which could contain either

02
15

i use the following line to count one up, but the output seems not to be two digit. So if 02 is the $version and count one up, it will give the output "3" and not "03". Sure if its already two digit, it works.

$((echo $version)   01))

how can I get bash to count with two digits and output it correctly?

CodePudding user response:

Use printf to format a number. Also, note that 08 fails in numeric expressions, as numbers starting with 0 are interpreted as octal.

#!/bin/bash

shopt -s extglob
for n in 02 08 15 001; do 
    i=${n## (0)}  # Remove leading zeros. Needs the extglob.
    length=${#n}
    printf "%0${length}d\\n" $((i   1))
done
  •  Tags:  
  • bash
  • Related