Skip to content
shellhacks.dev
Bash

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.

1 min read
Summarize in AI

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.

Shell
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}.log
Text
00042
ID-007
bash: line 4: printf: 08: invalid octal number
00000
00008
file08.log
file09.log
file10.log
file11.log

printf '%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.

Share

More snippets

Bash

Reverse a String in Pure Bash Without rev

Reverse a string in pure Bash with a for loop and substring expansion. It handles UTF-8, but it took about 2 seconds for 20000 characters where rev took 2 milliseconds.

1 min read

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.