9

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 '!$' !$

2 Answers 2

8

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.
2

echo simply iterates its arguments and sends them to standard out.

All of the magic is done by the shell: The shell substitutes some pattern for others. such as variables ( starting with $ ), history (starting with !), etc.

See the bash manual for more detail.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .