Bash – understanding the output of echo followed by some exlamation marks

bashecho

I was playing with echo $$ a while back. Well that displays that pid of the shell. But then I did echo ! which promptly displayed !. Then echo !! produced

echo echo !
echo !

$echo !!! gave

echo echo echo !!
echo echo !!

I couldn't understand the outputs. As far as I know, echo !! gives the last command that was executed on shell. But the outputs that I get here are weird for me to understand. I use bash shell.

Best Answer

The history event designator !! is replaced by the last command in your history. Bash first prints out the command how it will be executed, then executes it.

Example:

$ foo
foo: command not found
$ !!
foo                     # command to be executed
foo: command not found  # result of execution

In your case:

$ echo !
!
$ echo !!
echo echo !         # command to be executed
echo !              # result of execution
$ echo !!!
echo echo echo !!   # command to be executed
echo echo !!        # result of execution

Note that a command with an event designator is not inserted into history as typed. First the event designator gets expanded and then the command is entered into history. That is why in the third command (echo !!!), the event designator is not replaced by echo !! (the typed second command), but by echo echo ! (the expanded second command).

Here is the last command again with the replaced part highlighted:

$ echo (!!)!
echo (echo echo !)! # command to be executed
echo echo !!        # result of execution
Related Question