Bash uses exclamation marks for history expansions, as explained in the answers to this question (e.g. sudo !!
runs the previous command-line with sudo
). However, I can't find anywhere that explains what running the following command (i.e. a single exclamation mark) does:
!
It appears to print nothing and exit with 1, but I'm not sure why it does that. I've looked online and in the Bash man page, but can't find anything, apart from the fact that it's a "reserved word" – but so is }
, and running this:
}
prints an error:
bash: syntax error near unexpected token `}'
Best Answer
The lone
!
at the start of a command negates the exit status of the command or pipeline: if the command exits0
, it will flip into1
(failure), and if it exits non-zero it will turn it into a0
(successful) exit.This use is documented in the Bash manual:
A
!
with no following command negates the empty command, which does nothing and returns true (equivalent to the:
command). It thus inverts the true to a false and exits with status 1, but produces no error.There are also other uses of
!
within thetest
and[[
commands, where they negate a conditional test. These are unrelated to what you're seeing. In both your question and those cases it's not related to history expansion and the!
is separated from any other terms.