Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Double exclamation in bash script

Tags:

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 ?) 
like image 346
Sam Avatar asked Jul 27 '14 11:07

Sam


People also ask

What is double exclamation in Linux?

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. Follow this answer to receive notifications.

What does exclamation mark do in bash script?

Bash maintains the history of the commands executed in the current session. We can use the exclamation mark (!) to execute specific commands from the history.

What does != Mean in bash?

The origin of != is the C family of programming languages, in which the exclamation point generally means "not". In bash, a ! at the start of a command will invert the exit status of the command, turning nonzero values to zero and zeroes to one.

How do I escape exclamation mark in bash?

In addition to using single quotes for exclamations, in most shells you can also use a backslash \ to escape it.


2 Answers

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 
like image 87
Barmar Avatar answered Oct 09 '22 23:10

Barmar


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.

like image 43
konsolebox Avatar answered Oct 10 '22 00:10

konsolebox