Bash Shortcuts For Maximum Productivity

It may or may not surprise you to know that the bash shell has a very rich array of convenient shortcuts that can make your life, working with the command line, a whole lot easier. This ability to edit the command line using shortcuts is provided by the GNU Readline library. This library is used by many other *nix application besides bash, so learning some of these shortcuts will not only allow you to zip around bash commands with absurd ease :), but can also make you more proficient in using a variety of other *nix applications that use Readline. I don’t want to get into Readline too deeply so I’ll just mention one more thing. By default Readline uses emacs key bindings, although it can be configured to use the vi editing mode, I however prefer to learn the default behavior of most applications (I find it makes my life easier not having to constantly customize stuff). If you’re familiar with emacs then many of these shortcuts will not be new to you, so these are mostly for the rest of us :).

Bash Bang (!) Commands

Bash also has some handy features that use the ! (bang) to allow you to do some funky stuff with bash commands.

!! – run last command

!blah – run the most recent command that starts with ‘blah’ (e.g. !ls)

!blah:p – print out the command that !blah would run (also adds it as the latest command in the command history)

!$ – the last word of the previous command (same as Alt + .)

!$:p – print out the word that !$ would substitute

!* – the previous command except for the last word (e.g. if you type ‘find some_file.txt /‘, then !* would give you ‘find some_file.txt‘)

!*:p – print out what !* would substitute

There is one more handy thing you can do. This involves using the ^^ ‘command’. If you type a command and run it, you can re-run the same command but substitute a piece of text for another piece of text using ^^ e.g.:

Here, the command was the ^-al^-lash which replaced the –al with –lash in our previous ls command and re-ran the command again.

There is lots, lots more that you can do when it comes to using shortcuts with bash. But, the shortcuts above will get you 90% of the way towards maximum bash productivity. If you think that I have missed out on an essentialbash shortcut that you can’t live without (I am sure I have), then please let me know and I’ll update the post. As usual, feel free to subscribe to my feed for more tips and opinions on all things software development.

Share this:

Related

Great article; I love this kind of stuff, because you always discover something you forgot (or had never noticed before).

It might be worth pointing out that this command…

# Ctrl + xx – move between start of command line and current cursor position (and back again)

lets you operate with a mark ring, such that, if you Ctrl + xx from current cursor position to start of line, then manually move cursor to a new location, that new location will be swapped for ‘start of line’, so you have a rotating ring of ‘bookmarks’ based on current and last cursor position.

A favorite of my own: Alt+Backspace. Deletes backward one word. Respected in a surprising number of interfaces; particularly useful with filesystem/URI paths, as it understands the various portions of the string and will let you easily delete a portion at a time. Try it in your Location Bar.

http://www.skorks.com Alan Skorkin

That’s great info about backspace and especially cool that it works in browser location bar, thanks for the tip.

Late2theParty

Uh, a little late coming, but if Alt+backspace doesn’t work, Esc+backpace should also delete in the same manner.

http://www.davearonson.com/ Dave Aronson

Most of the Ctl and Alt hints will be familiar to users of Emacs (not to be confused with eMacs).

http://www.skorks.com Alan Skorkin

Yeah I mentioned at the top of the post that readline borrowed heavily from emacs, even though now emacs itself uses readline I believe :).

http://google.com/profiles/brianjosephking Brian J King

Great post – do you have by chance a great post/tutorial for generating SSH keys (especially with cPanel/WHM & OS X?

What about SCP (recursive) from a VPS to a local machine?

@brianjking me on twitter or reply here, although Twitter is easier. Cheers!

Thank you!

http://www.skorks.com Alan Skorkin

I was actually planning to do a general post about using ssh with linux, how keys come into it and what you need to do. I am not sure when I will write it up, but stick around and it will come up eventually.

http://ixmat.us Parnell Springmeyer

For the curious, a few of those command editing keyboard combinations are from Emacs; if you use Mac OS X (which integrates a few Emacs commands in the GUI too) some of those commands are a tad different. I won’t outline them here, as it should be straight forward to find a doc outlining them.

Cool post OP!

http://www.skorks.com Alan Skorkin

Yeah you’re right they are, there is no Alt key on a Mac (I think I am not a mac user) instead there is a meta key. So substituting Alt with Meta might work, but there is also another way. Many of the shortcuts listed have equivalents that use the Esc key which will work on Mac or Linux.

Thanks for the post. I already knew, and use, a bunch of these every day, but some of them just blew me away! I love the ^^ substitute shortcut; that one alone is set to revolutionise my Bash experience!

Its still useful but definitely good to know all the other commands. Now if I can just remember to use them…

http://www.skorks.com Alan Skorkin

Yeah I tend to use that one as well myself :). You’re right though, the most challenging thing is teaching yourself to actually use the shortcuts in the first place.

sati

and today, four years onward, this blog post ist still useful :) came accross this while trying to remember some keybindings I learnt about ages ago and then quickly forgot because keybindings for ctrl-cursor sequences & home/end keys are now activated by default in almost every distro and jumping to beginning or end of line or forward/backward between words is what I do most, I just forgot which ctrl-key combinations can be used for the fancier stuff and although I was sometimes reminded that there was some combination for something when it would have been useful to know, I never actually got round to taking a look again. that’s until now. and here’s what is almost guaranteed to help you “actually use the shortcuts”: login to your linux server with a windows client via putty; suddenly, the default keybindings no longer work (at least with a debian server). and believe me, it won’t take long before you notice you can’t do without and look for those long forgotten readline/emacs defaults (unless maybe if you’re more the customization type, which I’m not – I’m so too lazy to customize, that I’ll rather learn cryptic sequences :)). and once you open your mind to learning some new ctrl-key combinations (in a practical context?), there’s suddenly room for a few more as well. At least that’s how my brain seems to work.

Anyway: thanks for this nice posting (and the equally nice comments and additions below it); I especially enjoyed the way you casually strew in a bit of background info at the beginning, just enough to get an idea what is actually going on in the background and which part is responsible for what so that those who are interested have a cue to pick up on for further research and those who aren’t won’t be bored to death and still get an idea of the internals.

http://www.linkedin.com/samulution Aaron Samuel

Generating SSH keys is quite simple in linux
1. install openssh client & server or virtual packages depending on your OS using apt/yum/pkg/pacman or whichever way you install
2. switch to the username in which you want to create trust for , i.e.
su – aaron

3. Type ‘ssh-keygen -t rsa’ (or dsa if you like) follow the prompts people usually dont use passcode phrases and just press enter to all those questions

4. Type ‘ssh-copy-id -i ~/.ssh/id_pub.rsa username@host’ (or dsa if thats what you chose)
you can efficently omit username@ as you have already switched to the user but this is an example so to be full i use the full syntax.

5. Enter your password one time as prompted.

6. When that application exits you should now be able to ssh scp rsync via ssh all passwordless.

http://www.linkedin.com/samulution Aaron Samuel

In regards to history | grep
cat /home/*/.bash_history | grep is killer from security standpoint…
I love those ones but you’ll get kick out of

type CTRL + r (ctrl plus the r button) …get a prompt like below

[1] rainofkayos@rain ~ % [482]
bck-i-search: _

once there just type some letters from what you think the command contained, it will come up with the last whole line you type in bash that matches it,, you can continue to sort the results further back by holding CTRL and keep pressing r…once you found it,, just type the right direction key and there it is ready for you to press ENTER… i know that sounds like a lot but,, when you get the hang of it its rather snazZy =)

Instead of pressing up to find a previous command, just type in the first few letters of a previous command and bash will scroll through commands that started with those letters.

For example, say you used vim to open a file some time ago. Type v, then press up , up , up…etc until you find the vim command you were looking for. This is a faster, simpler alternative to the Ctrl-R search, which is so useful.

BTW, nice write up, thanks author.

Nice writeup, thanks.

http://www.skorks.com Alan Skorkin

That’s a good one I like it, definitely gonna be adding it to my bag.

Tim

This really nice. Allowing normal history navigation with up and down arrows as before and then a focused search by typing the frist few letters and then using the up and down arrows to navigate just those commands in history starting with the same letters. However, mac users will need to install the bash-completion file, which is not part of the standard mac os x package. See below.

I believe this is also standard in ZSH or at least a standard part of the OhMyZSH plugin. It’s hard to tell which is which sometimes.

http://twitter.com/aleksands Aleksandersen

This list was really useful, thanks. Your descriptions were better than the list of bash shortcuts in Wikipedia.

wise guy

You have a mistake: bang-star (!*) is “all the arguments of the last command” not “the previous command except for the last word” as you say.

Not nearly as useful as bang-dollar. Bang-dollar is good for stuff like

ls -l foo.txt
rm -f !$

Mike

My personal favorite is CTRL+o. Pick a command from your history and hit enter, this executes the command and presents a blank prompt. If you hit CTRL+o after picking a command from your history, the command is executed, and the next command from history is prepared on the prompt.

Say you often execute a number of commands in sequence, but want to look over the output of each before continuing. Your session may look something like this:

It’s easier on pc keyboards than mac ones but I really like alt-# which prefixes the start of the line with a # and presses enter so it’s in the history but not executed…

Pingback: jaux.net()

suoranciata

my fav bash shortcut is zsh 8)

http://rhodesmill.org/brandon Brandon Craig Rhodes

Note that “Ctrl-s” pausing the screen is not a Bash feature (since Bash does not even have control of the screen while a command is running); instead, it is a feature of Unix terminals in general that have the “stty ixon” mode established. You can check whether it is on by typing “stty -a” and can turn it off with “stty -ixon.” I leave it turned off in my .profile, because letting the terminal intercept “Ctrl-s” never lets Bash see it, and it is one of Bash’s most useful readline features: “Ctrl-s” searches FORWARD through your history, so that after you have started a search with “Ctrl-r” and looked back through a few matching commands, you can hit “Ctrl-s” to start cycling forward back through the matches. You can “Ctrl-r” and “Ctrl-s” to your heart’s content until you’re sure you’ve found the version of the command you want. But only if you remember to “stty -ixon”!

Hi there!
First, thanks a lot for sharing such useful and great tips.
Second, I would like to do a litte correction about the !* usage.
You mentioned the following:
!* – the previous command except for the last word

This isn’t true.
In fact, !* gives you all the arguments passed, i.e, all of the words but the zeroth.
So, by doing something like:

echo a b c d e

then !!:*:p

will have as its output: a b c d e

Got it?
That’s it!
Thanks again and please keep up the good work.
Regards,

http://www.chuckvose.com Chuck Vose

You are a rockstar. I learned a couple things but I’m most stoked about ^^ and $!/$*. Really awesome.

This all works in ZSH as well so far which makes me terrifically happy. Thank you so much!

Jason

You forgot to mention that the ^^ command will only replace the first occurrence. Use the ^^^ command to replace all the occurrences (which I feel is more useful, for example, when replacing filenames). Just add another ^ at the end:

^search^replace^

http://morgangoose.com Morgan Goose

That doesn’t replace all occurrences for me? I use !!:gs/search/replace/ for that.

http://hepaestus.com/hepaestus Pete

How about a way to get the output of the previously completed command? For some reason I wish i could do this all the time.

Say I ran a grep in the previous command and I want to take that output as a $VAR and input it into the next command once I verify/see it.

For me, the sequence Ctrl+x Ctrl+e is very helpful: it opens your favorite editor to enter any (complex) command. After saving and quitting the editor, bash executes that command.

http://twitter.com/csgui Christian Guimarães

Awesome tip.

Martin Larsen

Nice tip! One drawback though is that you apparently can’t cancel a command. Let’s say you accicentally with ctrl-r recall a command that erases everything and then starts the editor with ctrl-x ctrl-e. Only now you discover you recalled the wrong command and immediately leaves the editor. Bad luck! Bash will wipe your disk promptly!

It would be much much safer if you ended on the commandline and had to press Enter to actually execute the command.

Solomon White

You can cancel an editing session in vim — use the command :cq, which should take you back to the command line as it was when you brought up the editor. I assume there’s something similar in emacs.