Skip to main content

10 Useful Tips for Using the Exclamation Mark (!) in Linux

·428 words·3 mins
Bash Linux Shell
Table of Contents

The exclamation mark (!) in Linux Bash can serve as a logical negation operator or a powerful shortcut to work with command history. With it, you can re-run, modify, or reference previously executed commands efficiently.

Below are 10 useful techniques for using ! in Linux, tested in the bash shell (though some may not work in other shells).


1. Run a Command from History by Number
#

$ history
$ !1551

Runs the command listed at number 1551 in history.


2. Run Previous Commands by Relative Position
#

$ !-6
$ !-8
$ !-10

Runs the 6th, 8th, or 10th-to-last command.


3. Reuse the Last Argument from the Previous Command
#

$ ls /home/$USER/Binary/firefox
$ ls -l !$

!$ inserts the last argument of the previous command.


4. Work with Multiple Arguments
#

$ cp /home/avi/Desktop/1.txt /home/avi/Downloads
$ echo "1st: !^"
$ echo "2nd: !cp:2"
  • !^ = first argument
  • !cp:2 = 2nd argument from last cp
  • !* = all arguments

5. Run a Previous Command by Keyword
#

$ !ls -l

Runs the last command that started with ls -l.


6. The Magic of !!
#

$ apt-get update
$ sudo !!

Repeats the last command (!! expands to it).


7. Use ! for Logical NOT with File Patterns
#

$ rm !(2.txt)
$ rm !(*.pdf)

Deletes everything except specified files.


8. Check if a Directory Exists
#

$ [ ! -d /home/rumenz ] && printf 'No dir\n' || printf 'Exists\n'

9. Exit if Directory Does Not Exist
#

$ [ ! -d /home/rumenz ] && exit

10. Create a Directory if It Does Not Exist
#

$ [ ! -d /home/rumenz ] && mkdir /home/rumenz

Quick Reference Cheatsheet
#

Tip Command Example Description
1 !1551 Run command #1551 from history
2 !-3 Run the 3rd-to-last command
3 ls -l !$ Reuse last argument
4 !^, !xyz:2, !* Reuse 1st, nth, or all args
5 !ls -l Run last command starting with keyword
6 !!, sudo !! Repeat last command (useful with sudo)
7 rm !(2.txt) Delete all except 2.txt
8 [ ! -d dir ] && printf "No\n" Check if directory exists
9 [ ! -d dir ] && exit Exit if directory missing
10 [ ! -d dir ] && mkdir dir Create directory if missing

Final Thoughts
#

The exclamation mark ! is far more than just a negation operator. In Bash, it provides shortcuts for reusing history, arguments, and even controlling file operations with patterns. Mastering these 10 tips can save you time, prevent errors, and boost your efficiency on the Linux command line.

Related

600 Essential Linux Commands for Developers and Sysadmins
·1004 words·5 mins
Linux Linux Commands Sysadmin DevOps Server Management
Updating Embedded Linux System Images: Wind River Linux vs Ubuntu Core
·1027 words·5 mins
Embedded Linux Linux System Image Update Wind River Linux
Using the envsubst Command to Replace Environment Variables
·393 words·2 mins
Envsubst Linux Shell Script Environment Variables