'Bash - Remove leading zero for numbers with double digits

I have a variable in bash number which contains values 01, 02, 03, 04, 05, 06, 07, 08, 09, 010, 011, 012.

I would like to remove the leading zeros before 010, 011 and 012. I only want to remove the leading zeroes if the number is a double digit number.

How can I achieve this?

Thanks in advance!



Solution 1:[1]

Try:

a="012"
printf '%02d\n' "$((10#${a}))"
12

Solution 2:[2]

Another way:

a="014"
printf "%02d\n" $(echo "obase=10;$a" |bc)
14

another one:

[[ $a =~ ^0+[1-9]{2,}$ ]] && a="$(echo $((10#${a})))"
echo $a

This one will remove all 0s from beginning for 2 or more non-zero digit numbers.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2