bash-bang - Linux


The !! command in Linux is a shell shortcut to repeat the last command executed. This is particularly useful for re-executing the previous command quickly; it’s commonly used in situations where you need to prepend something to the last command (like sudo), or if there was a typo in the previous command that you corrected.


The syntax for using !! is very simple:


This command doesn’t take any parameters or options. When executed, the shell replaces !! with the previously executed command and runs it again.


Since !! is a shell feature rather than an independent command, it does not have any options or flags. Its behavior is solely to repeat the last command executed in the shell.


Here are some practical examples demonstrating common uses of !!:

  1. Re-running the last command with elevated privileges:

    $ apt-get update
    Permission denied
    $ sudo !!

    The sudo !! command repeats the last command (apt-get update) but prefixes it with sudo to run it with administrative privileges.

  2. Correcting a typo quickly:

    $ ech "Hello, World!"
    bash: ech: command not found
    $ echo "Hello, World!"
    Hello, World!
    $ !!
    Hello, World!

    In this example, after correcting the typo from ech to echo, using !! re-executes the corrected command.

Common Issues

  1. Command Context:

    • The !! command only knows about the last command executed in the current shell session. Therefore, if used in a different session or tab, it would not be aware of the commands executed elsewhere.
  2. Safety in Scripting:

    • It’s not recommended to use !! in scripts because the command it refers to can change. Always explicitly specify commands in scripts for clarity and safety.


!! can be integrated with other Linux commands for more complex tasks. For example, if you forgot to add sudo to a command that requires root privileges, you can simply use:

$ sudo !!

Another common integration is with watch, to continuously repeat the last command at regular intervals:

$ watch !!
  • !$ – Repeats the last word of the previous command. Commonly used to operate on the same file or directory.
  • !n – Re-executes the nth command in history.
  • !?string? – Re-executes the most recent command containing string.

These history expansion features are provided by shells like bash and zsh, which interpret these commands before execution. For more insights on history commands, checking the shell’s manual (man bash or man zsh) is recommended.

This overview and instructions should provide a clear and straightforward understanding of how to effectively use the !! command in various Linux environments.