Lesson 6 | Modifying the previous command |
Objective | Use the history feature to modify and replay the previous Unix command. |
Unix history substitution allows you to modify and replay the most recent command efficiently. This lesson focuses on two simple techniques: quick substitution for fixing errors and word substitution for reusing parts of the previous command.
These shortcuts improve your speed, reduce typing errors, and are especially useful in command-line environments like scripting, remote SSH sessions, or systems administration where retyping long paths or correcting typos can be tedious.
Quick substitution lets you fix errors in the previous command using the following syntax:
% ^old^new
Start with a caret (^
), followed by the incorrect text (old
), another caret, and the correct text (new
).
Example:
% cp indxe.html index.html.backup indxe.html: no such file or directory
Correct the filename typo:
% ^xe^ex
This reruns the command as:
cp index.html index.html.backup
Use !!
to rerun the last command exactly. Combine with sudo
like this:
sudo !!
Word substitution lets you reuse specific parts of the previous command’s arguments in a new command.
Substitution | What it substitutes |
---|---|
!$ | Last argument of previous command |
!^ | First argument of previous command |
!* | All arguments of previous command |
Example command:
% cat w x y z
Using word substitution after cat w x y z
:
Next Command | Actual Command Produced |
---|---|
% ls -l !$ | % ls -l z |
% ls -l !^ | % ls -l w |
% ls -l !* | % ls -l w x y z |
History Shortcut | Description |
---|---|
!! | Repeats last command |
^old^new | Substitutes old with new in previous command |
!$ | Last argument from previous command |
!^ | First argument from previous command |
!* | All arguments from previous command |
Type the following into a Unix terminal to test it out:
$ echo welcome.txt $ cat ^echo^touch
This will run:
touch welcome.txt