How do you pad the history number in the PS1 prompt with 0's?

Viewed 101

I want to create a bash prompt that starts with the history number padded with zeros, so that it is always at least three characters long:

001 user@hostname:~ $

I tried padding the special PS1 symbol \! with printf:

function padded_history {
    printf "%03d" "\!"
}
PS1="$(padded_history) \u@\h:\w \$"

But I get the following error:

-bash: printf: \!: invalid number
1 Answers

The escape sequence \! must be embedded in the value that is assigned to PS1. And you need to use single quotes around the value to prevent premature expansions.

PS1='$(printf "%03d" "\!") \u@\h:\w \$ '
Related