! as a prefix to some string will execute whatever command in the command buffer that starts with the (partial) string given. There are also some other uses for it. See e.g. Understanding the exclamation mark (!) in bash

My question is, how can I preview what command will be executed before executing it? E.g. if I do !for, and I've written several commands starting with 'for' previously, but I'm not completely sure if the one I think was the last one is indeed the one I think. It would be very useful if bash could show me what the command that would be executed is before I actually execute it. Is there any way to do this in bash?


5 Answers 5


Bash has inherited the ! mechanism from csh. The way to preview your command in both shells is to add a :p to the end.


You can use histverify shell option:

    If set, and readline is being used, the results of history substitution
    are not immediately passed to the shell parser.  Instead,
    the resulting line is loaded into the readline editing buffer,
    allowing further modification.


$ shopt -s histverify
$ !shopt

Another useful option is histreedit:

    If set, and readline is being used, a user is given the opportunity
    to re-edit a failed history substitution.

I usually abstain from (IMO broken) ! substitution and use the shell history functions instead; e.g. in vi-mode (you will certainly find equivalent options in emacs-mode) you'd search for the last occurrence, with your example that would be <Esc> / for <Enter>, and (if it's not the command you wanted) repeat search for the next appearance of for using the key n (or N to go in the other direction), and confirm the desired command with <Enter>.


You can map readline commands history-search-backward and history-search-forward to something (I'm using PgUp and PgDown) and use them to navigate through history instead of !.


If you're using vi mode (set -o vi) hit Esc or C-[ and k or UP to go up in history and j or DOWN to go down. You can edit what you've arrived at or execute it with Enter.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .