Sam
Sam

Reputation: 365

Double exclamation in bash script

I know when double exclamation is printed, it executes the previous command. But echo !! gives some strange results which I don't understand. For example when typed below command in bash script, it prints echo too as part of the output

echo $$
echo !!
This prints the below output:
echo echo $$
echo 3150
(Why does echo precede every output ?)

Upvotes: 30

Views: 20759

Answers (2)

konsolebox
konsolebox

Reputation: 75588

It's caused by history expansion. Quote it instead:

echo '!!'
echo \!\!

Or disable history expansion:

shopt -u -o histexpand  ## Or
set +H

See History Expansion.

Upvotes: 5

Barmar
Barmar

Reputation: 782364

When you use history substitution, the shell first displays the command that it's about to execute with all the substitutions shown, and then executes it. This is so you can see what the resulting command is, to confirm that it's what you expected.

So if you type:

some command
echo !!

the !! is replaced with the contents of the previous command. So it displays and then executes

echo some command

Upvotes: 36

Related Questions