Bash - Prepend Zero to Single Digit in While Loop

Bash - Prepend Zero to Single Digit in While Loop

I made this script exif_script And want to change ep variable to double digit Eg 01 instread of 1.

#!/bin/bash
x=0
ep=1
while [ $x -le 11 ]
do
  echo "Welcome $x times"
  date --date="$x week" +"%Y:%m:%d"
  exiftool -exififd:dateTimeOriginal="$(date --date="$x week" +"%Y:%m:%d") 00" $1$ep*
  x=$(( $x + 1 ))
  ep=$(( $ep + 1 ))
done
6

3 Answers

You can use shell parameter expansion to add zero-padding to numbers.

For example, to print number in a 5-digits format:

$ zeroos="00000"
$ number="123"

$ temp_num="$zeroos$number"
$ echo "${temp_num:(-5)}"
00123

# Or instead of the "5" constant, use $zeroos length
$ echo "${temp_num:(-${#zeroos})}"    
00123

Update:

Above example cuts off the front-most digits of $number, when the number becomes longer (with more digits) than $zeroos:

$ number="1234567" # Changed to 7 digits
echo "${temp_num:(-5)}"
34567 # Resulted in a wrong number!

A safer way:

$ number="123"
$ echo "${zeroos:${#number}:${#zeroos}}${number}"
00123

$ number="1234567"
$ echo "${zeroos:${#number}:${#zeroos}}${number}"
1234567

Note 1:

A slightly different variant, to use the first digits of $zeroos resp. $century (instead of the last ones) would be:

$ century="2000"
$ year="1"
$ echo "${century:0:-${#year}}${year}"
2001

This comes in handy for example, if you have mixed dates with 1-, 2- or even 4-digit years, but want them to be 4 digits in any case, without the need of conditions (for checking their actual digits) and any arithmetic.
The downside is, if ${#year} gets greater than ${#century}, this results in an error.

Note 2:

When using printf (as suggested on other answers), be aware that it could be mush slower on a large scale (see an example).

1

Using your script, the following will work.

#!/bin/bash
x=0
ep=1
while [ $x -le 11 ]
do
  ep_padded=$(printf '%02d' $ep)
  echo "Welcome $x times"
  date --date="$x week" +"%Y:%m:%d"
  exiftool -exififd:dateTimeOriginal="$(date --date="$x week" +"%Y:%m:%d") 00" $1$ep_padded*
  x=$(( $x + 1 ))
  ep=$(( $ep + 1 ))
done

You can use the following form to increment your variables too

x=$((++x))
ep=$((++ep))
5

set your variable as below, this will add a padding zero, you can add more zeros in case of your expectations.

ep="$(printf '%02d' $((++ep)) )"
3

Your Answer

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

Chloe Bennett
Author

Chloe Bennett

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.