Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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.

share|improve this question
add comment

2 Answers 2

up vote 11 down vote accepted

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 is. It gets expanded and then entered to the history. That is why in the third command (echo !!!), the event designator is not replaced by echo !!, but by echo echo !.

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

$ echo (!!)!
echo (echo echo !)! # command to be executed
echo echo !!        # result of execution
share|improve this answer
add comment

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 !

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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