I'm working with a command-line tool that provides a number of subcommands that all use the same binary, e.g. tool foo, tool bar, etc, and as I work, these commands are placed into my Bash shell history, for example:

 7322  [2021-04-16 15:37:45 +0000] tool foo .
 7323  [2021-04-16 15:37:47 +0000] tool bar
 7324  [2021-04-16 15:37:50 +0000] tool baz
 7325  [2021-04-16 15:38:01 +0000] tool qux -a -b asdf -c=100 /var/lib/foo/...
 7326  [2021-04-16 15:38:15 +0000] htop
 7327  [2021-04-16 15:38:21 +0000] tool foo . -x

The exact tool is proprietary (its exact functionality is irrelevant) and doesn't have specific features to help with tracking and recalling its own commands.

For example, I'd like to recall command 7325, tool qux -a -b asdf -c=100 /var/lib/foo/... (suppose that it's not recent enough to just hit the up arrow a bunch of times). The commands and parameters vary often enough that establishing a Bash alias doesn't seem practical or convenient (either I edit .bashrc or I lose the alias when the shell closes). I'm pretty confident that the last time I ran tool qux, it had the correct parameters that I would want to use, or a reasonably safe set that I would need to edit anyway.

I know I could run history | grep qux to look for the history index and then run !7325. Is there a way I can directly recall it with one set of keystrokes typed into the Bash prompt? !tool qux doesn't work because in this scenario it will run tool foo . -x qux instead. I tried quoting it, but it looks like expansion happens earlier.

  • Have you tried with Ctrl+R?
    – terdon
    Apr 16, 2021 at 16:13
  • @terdon I didn't before your comment, but that answers the question. Do you want to add an answer, should I self-answer, or should this get closed (against a dupe I didn't find or otherwise)?
    – nanofarad
    Apr 16, 2021 at 16:28
  • 1
    Great! I just posted an answer. I just wanted to be sure that it was indeed what you needed.
    – terdon
    Apr 16, 2021 at 16:34

1 Answer 1


You can use bash's "reverse interactive search", usually accessible via Ctrl+R. That key combination will bring up this prompt:


There, you can start writing the command and it will autocomplete from your history, with the most recent first. However, it matches the entire string you enter, so tool q will immediately bring back tool qux -a -b asdf -c=100 /var/lib/foo/.... That should do what you want.

From man bash:

       reverse-search-history (C-r)
              Search backward starting at the current line  and  moving  `up'
              through  the  history  as  necessary.   This  is an incremental
  • also worth mentioning: you can run the recalled command as-is by hitting enter. or you can edit it by pressing the left or right arrow key (or home/end/ins/del, or ^X^E to edit in $EDITOR).
    – cas
    Apr 17, 2021 at 2:54

You must log in to answer this question.

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