In previous tips Bash Terminal keyboard shortcuts and Handy Bash Shell Aliases, we started mentioning some useful shortcuts and aliases. But did you know about the Ctrl-R shortcut?
Here is how recalling a command works:
While in a terminal window running a Bash shell (the default shell for Shaheen), press Ctrl key and push R (noted Ctrl-R). The line will read (reverse-i-search): followed by the cursor. To find a previous command, type its first letters. As you type, the first matching command shows. For instance, if you search a previous sbatch command, press 's', then 'b', then 'a' till the first command beginning by 'sba' appears.
- If it suits you, press Ctrl-O or hit Return to execute it,
- if you need to modify it, press the right arrow. the (reverse-i-search) prompt disapears and place you back in normal mode and allow further editing before hiting Return when satisfied,
- If you search a similar one but typed earlier, hit Ctrl-R again and again. You will navigate along all the commands of your Bash history,
- if you change your mind, hit Ctrl-G to exit the current search and go back to an empty Bash prompt.
As smartly pointed in this blog post, you can label your favorite commands and use ctrl-R to find them instantaneously. Here is the trick:
- imagine that you use extensively the following command ' ls /project/kxxxx/DIR1/DIR2/DIR3/Results'...
- Just once, type the following
ls /project/kxxxx/DIR1/DIR2/DIR3/Results #res
- bash will completely ignore #res at the end of the line, as it is a comment... but it will be saved in your command history as is!
- From now on, just hit Ctrl-R (to search previous command) then hit '#', 'r', 'e', 's' to get back to it!
For a comprehensive list of Bash shortcuts check also here