Pad a Number with Leading Zeros in Bash with printf
Pad a number to a fixed width with printf %05d, and store it without a subshell using printf -v. A value with a leading zero, such as 08, is read as octal in Bash.
You need an identifier or a file name with a fixed number of digits, such as 00042, and do not want to call an external tool.
printf '%05d\n' 42
printf -v id 'ID-%03d' 7
echo "$id"
printf '%05d\n' 08
printf '%05d\n' $((10#08))
printf '%s\n' file{08..11}.log00042
ID-007
bash: line 4: printf: 08: invalid octal number
00000
00008
file08.log
file09.log
file10.log
file11.logprintf '%05d' pads with zeros to five digits, and printf -v name writes the result into a variable instead of printing it, so no subshell is needed. Brace expansion with a leading zero, as in {08..11}, produces padded numbers by itself. The trap is a value that already has a leading zero: printf %d reads 08 as octal, reports invalid octal number and prints zeros. Forcing base ten with 10#08 inside arithmetic fixes it. The format rules are under the printf builtin.
printf -v needs Bash 3.1 or later and is not in POSIX sh, where the portable form is id=$(printf 'ID-%03d' 7). The same octal rule applies to numbers read from input, so strip leading zeros before doing arithmetic on them.