In Linux, the “!” command, also known as the history expansion feature, allows you to recall and execute commands from your command history using various syntax options. Here’s an overview of how to use the “!” command:
- Open a Terminal:
Launch a terminal emulator on your Linux system. - Recall and Execute a Specific Command:
The basic syntax of the “!” command is to use an exclamation mark followed by a command number. For example, to rerun command number 123 from your command history, type:
!123
The “!” command will replace itself with the corresponding command from the history and execute it.
- Recall and Execute the Most Recent Command:
To quickly rerun the most recent command from your history, you can use a single exclamation mark (!) without specifying a command number. For example:
!!
This will execute the previous command in your history.
- Recall and Execute a Command Starting with a Specific String:
You can use the “!” command to recall and execute the most recent command that starts with a specific string of characters. For example, to execute the most recent command that starts with “ls”, run:
!ls
The “!” command will search the command history for the most recent command that matches the provided string and execute it.
- Recall and Execute a Command by Partial String Match:
The “!” command can also be used to recall and execute a command by partial string matching. For example, to execute the most recent command that contains the string “foo”, run:
!?foo?
The “?” characters act as placeholders and match any character. This syntax allows you to match a command by specifying a partial string.
- Using Command Substitution:
You can also use command substitution with the “!” command. For example, to recall and execute the most recent command starting with “ls” and append additional arguments, run:
!ls:*
The “:*” syntax instructs the “!” command to substitute the matching command and append additional arguments after the colon.
- Exiting the Command:
The “!” command will replace itself with the corresponding command from the history and execute it. Once the command is executed, you will see the output and return to the command prompt. You can continue entering new commands or exit the terminal as needed.
The “!” command provides a convenient way to recall and execute commands from your command history based on command numbers, strings, or patterns. It can save you time by avoiding the need to retype long or complex commands and allows for flexible command substitution.