bashunix

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 ?)

Solution

  • 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