shell script set the default numbers as double digit zero as prefix

In a shell script, I’m processing, some addition process will print an output. If it is a single-digit one, then it has to add zero as a prefix.

Here is my current script:

c_year=2020
for i in {01..11}
        do  
            n_year=2020
            echo 'Next Year:'$n_year
            if [[ $i == 11 ]]
            then n_month=12
            echo 'Next Month:'$n_month
            else 
            n_month=$(($i + 1))
            echo 'Next Month:'$n_month
            fi
            echo $date" : Processing data '$c_year-$i-01 00:00:00' and '$n_year-$n_month-01 00:00:00'"
        done

The i value is in doule digit, but the n_month is still printing single digit. How do I set default shell output should return as double digit?

Or any alternate way to solve this?

Asked By: TheDataGuy

||

I think this is a possibility, simplifying:

for i in {1..11}; do  
    n_month=$(($i + 1))
    [[ $n_month =~ ^[0-9]$ ]] && n_month="0$n_month"
    echo "$n_month"
done

Output

02
03
04
05
06
07
08
09
10
11
12

Do not use leading zeros in variables where you want to store decimal values because in various contexts a number with leading zero is interpreted as octal. Arithmetic expansion is one of these contexts. The following code fails:

i1=09
i2=$((i1+1))

while this one works:

i1=9
i2=$((i1+1))

Add leading zeros only when printing the results. Do this by using printf with a proper format. Example:

i1=9
i2=$((i1+1))
year1=2020
year2=2020

printf "Processing data '%04d-%02d-01 00:00:00' and '%04d-%02d-01 00:00:00'n" "$year1" "$i1" "$year2" "$i2"


Note when printf expects a number, it interprets a string with leading zero as octal number. So this is another context where you need to be careful. Example:

$ printf '%02dn' 9
09
$ printf '%02dn' 09
printf: '09': value not completely converted
00
$ printf '%02dn' 012
10

This means while printf %02d can be a solution when you avoid leading zeros, it may be a bug when you don’t.

Answered By: Kamil Maciorowski
Categories: Answers Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.