Bash – Why does Bash history not record this command

bashcommand lineprintf

The command printf "#!/bin/bash\n" > t generates an error(bash: !/bin/bash\n": event not found), but hitting the up key does not recall the command so that I can modify it. Why is that?

(What I was trying for here can be accomplished with printf "%s\n" '#!/bin/bash' >t I am trying to learn Bash and really want to understand why bash history doesn't capture the previous printf command.)

Best Answer

The ! character triggers history expansion, as you discovered. This step occurs before a command is saved to the history, so that it can saved into the history with the expansion already done. When an error occurs in history expansion, bash stops processing the command, and so it never gets saved into the history.

History expansion allows previous commands or parts of previous commands to be substituted into the current command. If this was done before saving the command to the history, it could mean something different each time it is executed, because the previous commands are different in each instance. See http://www.gnu.org/software/bash/manual/bashref.html#History-Interaction

For reference, zsh's behavior is different. It will save the command but with the history expansion missing.

Related Question