0

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?

2
  • Could you clarify what is special about 11? Wouldn't 10 be in the same situation, being a double digit? If I understand correctly. – schrodigerscatcuriosity Nov 9 '20 at 13:15
  • Thats for my use case, for year 2020, I have to print up to 11 if not 2020 then print up to 12. I cut the if part only here – Bhuvanesh Nov 9 '20 at 13:16
0

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
5

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 '%02d\n' 9
09
$ printf '%02d\n' 09
printf: '09': value not completely converted
00
$ printf '%02d\n' 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.