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.
set +H
to make it work – Valentin Bajrami Oct 29 '13 at 14:08printf '#!/bin/bash\n' > t
. That time as it's within Single Quotes, the "!" won't be interpreted as the special "!" history character and the command will work. – Olivier Dulac Oct 29 '13 at 18:27printf '\n'
does indeed print a newline, so @OlivierDulac's suggestion should work. The interpretation of\n
as a newline is being done byprintf
, not when reading the argument, so the kind of quotes doesn't matter. – wingedsubmariner Oct 29 '13 at 22:07