Bash – echo of a string with an exclamation point

bashcommand historyechoshell

Here are what I put in bash and the results I got about 'echo':

$ echo '!$'   
!$  
$ echo "!$"  
echo "'!$'"  
'!$'

I'd like to know how 'echo' deals with the second input. It seems to me that 'echo' would first print the strings (expand some if necessary) you entered, then execute certain if they are executable.

A more mind-blowing example I can construct but am not able to understand is:

$ echo '!$'  
!$  
$ echo "!echo "!$""  
echo "echo '!$' "'!$'""  
echo '!$' !$

Best Answer

In command:

echo "!$"

!$ is expanded by bash before passed to echo. Inside double quotes, if enabled, history expansion will be performed unless you escape !, using backslash \. bash had done the expansion, echo does nothing here, it just print what it got.

!$ refer to the last argument of preceding command, which is string '!$'.

In your second example:

$ echo '!$'
!$
$ echo "!echo "!$""
echo "echo '!$' "'!$'""
echo '!$' !$

Command echo "echo '!$' "'!$'"", arguments passed to echo are divided in three parts:

  • First: "echo '!$' ", expanded to string echo '!$'.
  • Second: '!$', expanded to string !$.
  • Third: "", expanded to empty string.
Related Question