4

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.

12

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
| improve this answer | |
4

If you use !! that it is substituted by the last command in the shell, so the first line is the to show the substitution echo echo ! and the second one is the output echo !

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.