DEV Community

Discussion on: My Favorite Bash Tips, Tricks, and Shortcuts

Collapse
 
vonheikemen profile image
Heiker
# Up Arrow
bind '"\e[A": history-search-backward'

# Down Arrow
bind '"\e[B": history-search-forward'
Enter fullscreen mode Exit fullscreen mode

The history-search-* enable a "search by prefix".

Let's say I have this in my history.

node ./test.js
vi /tmp/text.txt
nvim /tmp/text.txt
echo "a string with vi in it"
vi /tmp/other-text.txt
Enter fullscreen mode Exit fullscreen mode

if I type vi and start pressing the up arrow bash will only show me the entries that begins with vi. Which is awesome. I have a couple of commands that have been on my history for months, and I have never typed them twice, it's always the first two letters + up + enter.

Here is another trick

# Space, but magical
bind Space:magic-space
Enter fullscreen mode Exit fullscreen mode

This one enables history expansion with the space key. So you can do sudo !! + space, and it will show you the entire command before you run it.

Collapse
 
nilkun profile image
Nilkun

Just copy-pasted your code into my .bashrc! That is an amazing trick!

Collapse
 
aashutoshrathi profile image
Aashutosh Rathi

Hey! Would you like to add this sorcery at github.com/aashutoshrathi/awesome-...?

Collapse
 
vonheikemen profile image
Heiker

Sure. I'll do that.

I would like to mention that I got this from the oh-my-bash repo. They have a ton of interesting things there.

Thread Thread
 
loebkes profile image
Lui

You should really have a look at github.com/junegunn/fzf

This changed my life and how I work with the command line forever.

Thread Thread
 
vonheikemen profile image
Heiker

Oh I know about fzf, I use it extensively inside vim (I would be lost without it). Sadly I don't have many use cases for it in my day to day.

But this reminds me of yet another thing you can do with bind. One can bind key sequence with a "macro", it's like simulating keystrokes.

I have these two.

# Alt + f 
bind '"\ef": "\C-e | fzf"'

# Alt + p
bind '"\ep": "\C-e | less"'
Enter fullscreen mode Exit fullscreen mode

Alt + f will append | fzf at the end of a command and Alt + p does the same but with less. This works by using the sequence \C-e (ctrl + e) which makes the cursor go to the end of the line and basically typing the rest for you.