Thursday, March 5, 2015

Add leading zero to integer in bash

I was composing a script that would store a file per day in the month, but wanted to have a leading zero not to mix up when dir listing. In bash, you have a couple of options.

1. Using range
#!/bin/bash
for i in {01..31}
do
   echo "Day: $i"
done

Works, but has downside that you cannot feed it with a variable.

2. Three-expression example
#!/bin/bash
for (( i=1; i<=31; i++ ))
do
   i=$(("0"$i))
   echo "Day: $i"
done

Will throw an error being: value too great for base (error token is “08”) Reason being that Bash will treat the variable as an octal, even with leading zero. Prepending the string "10#" to the front of your variable will have it treated as decimal by Bash.

3. Using printf
#!/bin/bash
for (( i=1; i<=31; i++ ))
do
   i=$(printf "%02d" $i)
   echo "Day: $i"
done

Works & easy solution, my favorite.

4. Using seq
#!/bin/bash
for i in `seq -f ‘%02g’ 1 31`
do
   echo "Day: $i"
done

Works also

No comments:

Post a Comment