How to Recall (Without Executing) a Specific Command from Bash History Using Prefix Search


6 views

Every developer knows the frustration of remembering that perfect command you ran yesterday, but needing to tweak just one parameter before re-executing. Bash's history mechanism provides several powerful ways to retrieve previous commands, but most methods immediately execute them.

The basic history recall syntax in bash includes:

!xyz      # Executes last command starting with "xyz"
!!        # Executes previous command
!n        # Executes command with history number n

To recall without execution, combine history search with the :p modifier:

!xyz:p    # Prints instead of executes

This will display the command in your terminal without running it, allowing you to:

  • Press ↑ to edit the recalled command
  • Modify parameters before execution
  • Copy portions for new commands

Basic usage:

$ git commit -m "initial version"
$ !git:p
git commit -m "initial version"  # Command displayed but not executed

Complex command modification:

$ docker run -it --rm -v $(pwd):/app ubuntu bash
# Need to change the volume mapping
$ !doc:p
docker run -it --rm -v $(pwd):/app ubuntu bash
# Now press ↑ and modify the -v parameter

For more control over history search:

Ctrl+R xyz  # Reverse search (interactive)
history | grep xyz  # Full history search

The :p modifier works with all history expansions:

!-2:p     # Recall command two back in history
!42:p     # Recall command with history ID 42

You can chain modifiers for powerful combinations:

!git:s/old/new/:p  # Substitute text then print

Every bash user knows the handy !xyz syntax that executes the last command starting with "xyz". But what if we want to recall that command for editing rather than immediate execution?

Append a colon (:) to prevent execution:

!xyz:p

This will:

  • Print the matching command
  • Add it to your command history
  • Not execute it
# First run some commands
$ git commit -m "initial version"
$ git push origin main
$ python myscript.py --verbose

# Later want to recall git commit command
$ !git:p
git commit -m "initial version"  # This prints but doesn't execute

For even more control:

# Search history interactively (Ctrl+R)
(reverse-i-search)git: git commit -m "initial version"

# Press Left Arrow instead of Enter to edit

For complex editing needs:

$ fc -l 245 250  # List commands 245-250
$ fc 245         # Edit command 245 in default editor

Recalling without execution is crucial when:

  • You need to modify parameters
  • The original command had destructive potential
  • You want to chain commands creatively

Combine with set -o histverify to always see expanded commands before execution:

$ set -o histverify
$ !git
$ git commit -m "initial version"  # Shows the command, waits for Enter