16

For example, in bash I can type !xyz which will run the last command I typed beginning with xyz.

How can I bring up the last command I typed beginning with xyz but without executing it?
e.g so I can change parameters before execution....

4 Answers 4

21

You can do it like this: On the command prompt press Ctrl+r and then type the command you want to recall, in your case xyz. This will show you the complete command without executing it.

1
  • 1
    More useful than ! notation, because you can press Ctrl-r multiple times to cycle further into matching history. When you arrive at the proper place, you can try to execute not with Enter but with Ctrl-o for much profit.
    – kubanczyk
    Mar 8, 2016 at 12:27
14

Try !xyz:p; it will recall the command to the top of history without executing it, so eg up-arrow can immediately access it for interactive editing.

As an aside, I make a practice of doing this when recalling commands with a regexp that could conceivably dig up something damaging, ever since a hasty !r, intended to recall the most recent rsync ... command, pulled back and executed an rm * that had been pushed to the stack more recently than the rsync.

4
  • Thanks, thats a good practice. I have done the same with a rm -rf ./* never been so grateful for a period. FYI The !xyz:p worked, thankyou, but required a few extra keystrokes than the ctrl-r solution.
    – Mtl Dev
    Mar 8, 2016 at 8:22
  • @MtlDev yes; I find the ^R solution works best for EMACSey folks, whereas the !-path works best for violators like me.
    – MadHatter
    Mar 8, 2016 at 8:33
  • +1 for answering the question. Accepted answer suggests an alternative but I think ! and Ctrl+r have different uses.
    – minnymauer
    Dec 20, 2021 at 20:40
  • Also note, zsh's default behavior is not to execute when recalling with !. I was hoping bash would have a setting to make this its behavior as well.
    – minnymauer
    Dec 20, 2021 at 20:41
1
  1. Execute the following command. It will echo the last executed command. you can copy and edit the command. This command tested in debian.

    history |tail -2 | grep -v history | cut -d ' ' -f4-

  2. Or Press and hold ctrl+R and type the starting letter of your last command. It will list the commands you executed previously based on your input. Once it shows desired command, just press right arrow in order to select that command.

1
  • 1
    The first command is so smooth !! I think it's faster to just look after the command in history than writing all of this ^__^ Mar 9, 2016 at 7:26
1

If reverse history search failed, do anything of:

$ history | grep WHAT_YOU_LOOK_FOR

Or:

$ grep WHAT_YOU_LOOK_FOR ~/.bash_history

You must log in to answer this question.

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