Unix Concepts   «Prev  Next»
Lesson 6Modifying the previous command
ObjectiveUse the history feature to modify and replay the previous Unix command.

Modifying 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.

Why It Matters

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

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

Common Use Case

  • Fixing typos in filenames or paths
  • Correcting mistyped options or switches

Quick Tip

Use !! to rerun the last command exactly. Combine with sudo like this:

sudo !!

Word Substitution

Word substitution lets you reuse specific parts of the previous command’s arguments in a new command.

SubstitutionWhat it substitutes
!$Last argument of previous command
!^First argument of previous command
!*All arguments of previous command

Example command:

% cat w x y z

When to Use

  • Copying the same file again to a different folder
  • Running different commands on the same set of files

Word Substitution in Action

Using word substitution after cat w x y z:

Next CommandActual Command Produced
% ls -l !$% ls -l z
% ls -l !^% ls -l w
% ls -l !*% ls -l w x y z

Quick Reference

History ShortcutDescription
!!Repeats last command
^old^newSubstitutes old with new in previous command
!$Last argument from previous command
!^First argument from previous command
!*All arguments from previous command

Try It Yourself

Type the following into a Unix terminal to test it out:

$ echo welcome.txt
$ cat ^echo^touch

This will run:

touch welcome.txt

Modify Command Exercise

Click the link below to practice using quick and word substitution in real examples:
Modify Command Exercise

SEMrush Software 6 SEMrush Banner 6