Bash Shortcuts For Maximum Productivity

MaximumIt 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 :).

Command Editing Shortcuts

  • Ctrl + a – go to the start of the command line
  • Ctrl + e – go to the end of the command line
  • Ctrl + k – delete from cursor to the end of the command line
  • Ctrl + u – delete from cursor to the start of the command line
  • Ctrl + w – delete from cursor to start of word (i.e. delete backwards one word)
  • Ctrl + y – paste word or text that was cut using one of the deletion shortcuts (such as the one above) after the cursor
  • Ctrl + xx – move between start of command line and current cursor position (and back again)
  • Alt + b – move backward one word (or go to start of word the cursor is currently on)
  • Alt + f – move forward one word (or go to end of word the cursor is currently on)
  • Alt + d – delete to end of word starting at cursor (whole word if cursor is at the beginning of word)
  • Alt + c – capitalize to end of word starting at cursor (whole word if cursor is at the beginning of word)
  • Alt + u – make uppercase from cursor to end of word
  • Alt + l – make lowercase from cursor to end of word
  • Alt + t – swap current word with previous
  • Ctrl + f – move forward one character
  • Ctrl + b – move backward one character
  • Ctrl + d – delete character under the cursor
  • Ctrl + h – delete character before the cursor
  • Ctrl + t – swap character under cursor with the previous one

Command Recall Shortcuts

  • Ctrl + r – search the history backwards
  • Ctrl + g – escape from history searching mode
  • Ctrl + p – previous command in history (i.e. walk back through the command history)
  • Ctrl + n – next command in history (i.e. walk forward through the command history)
  • Alt + . – use the last word of the previous command

Command Control Shortcuts

  • Ctrl + l – clear the screen
  • Ctrl + s – stops the output to the screen (for long running verbose command)
  • Ctrl + q – allow output to the screen (if previously stopped using command above)
  • Ctrl + c – terminate the command
  • Ctrl + z – suspend/stop the command

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.:

$ ls -al
total 12
drwxrwxrwx+ 3 Administrator None    0 Jul 21 23:38 .
drwxrwxrwx+ 3 Administrator None    0 Jul 21 23:34 ..
-rwxr-xr-x  1 Administrator None 1150 Jul 21 23:34 .bash_profile
-rwxr-xr-x  1 Administrator None 3116 Jul 21 23:34 .bashrc
drwxr-xr-x+ 4 Administrator None    0 Jul 21 23:39 .gem
-rwxr-xr-x  1 Administrator None 1461 Jul 21 23:34 .inputrc
$ ^-al^-lash
ls -lash
total 12K
   0 drwxrwxrwx+ 3 Administrator None    0 Jul 21 23:38 .
   0 drwxrwxrwx+ 3 Administrator None    0 Jul 21 23:34 ..
4.0K -rwxr-xr-x  1 Administrator None 1.2K Jul 21 23:34 .bash_profile
4.0K -rwxr-xr-x  1 Administrator None 3.1K Jul 21 23:34 .bashrc
   0 drwxr-xr-x+ 4 Administrator None    0 Jul 21 23:39 .gem
4.0K -rwxr-xr-x  1 Administrator None 1.5K Jul 21 23:34 .inputrc

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 essential bash 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.

Image by djhsilver

  • 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.

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

      • Jarno Ilari Suni

        Which browser?

    • Late2theParty

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

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

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

  • 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!

    • 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.

  • 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!

    • 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.

  • “Try it in your *browser’s* Location Bar”, that should read.

  • Fidel Ramos

    Wonderful compilation, I didn’t know Alt+.

  • James Martin

    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!

    • Yeah, I was pretty blown away when I learned about that one also :).

  • joão

    Nice article. Though it’s lib readline shortcuts, which emacs and bash incorporates. :)

    • Exactly, as I mentioned at the start of the post :)

  • Pingback: Susan Pinochet (sdp) 's status on Wednesday, 16-Sep-09 16:35:44 UTC -

  • Surki

    Put this in your ~/.inputrc
    “\e[A”: history-search-backward
    “\e[B”: history-search-forward
    “\C-p”: history-search-backward
    “\C-n”: history-search-forward

    Type something, then pressing Ctrl-p(or Ctrl-n) will initiate the search in the history with the already typed text as prefix

  • Pingback: Destillat KW38-2009 | - GNU/Linux, Open Source, Softwareentwicklung, Selbstmanagement, Vim ...()

  • Pingback: REVERT TO CONSOLE › Bash Shortcuts()

  • Before reading this article I was limited in bash tricks to…

    history | grep “something”

    where # was the line in history for the command.

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

    • 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.

  • 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 [email protected]’ (or dsa if thats what you chose)
    you can efficently omit [email protected] 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.

  • 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] [email protected] ~ % [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 =)

    • Yeah, CTRL-R is awesome, I use it all the time :)

  • Jesus Presley

    Great post. On behalf of all newbs – Thank you!

  • Pingback: Skróty klawiszowe w bashu -

  • Pingback: The Most Common Things You Do To A Large Data File With Bash | RZN's Rambles()

  • # Last command, last argument –> $_ to use in scripts
    wget -c http://path/to/file -O /path/to/save/name && chmod 0755 $_

    # Before perform any change make backup easy way
    cp /etc/apt/sources.list{,.backup}

  • Lee

    Everyone should read through the bash manual once a year. Tons of stuff in there.

    Some further details.

    1. $ set -o emacs makes the emacs commands work. $ set -o vi makes vi/vim commands work instead.

    2. ^C, ^Z, ^S, and ^Q are handled by the terminal device, and are set using the stty command.

  • Jim Bob

    Here’s one of my FAVORITE bash tricks.

    Add this to /home/.bashrc

    bind ‘”\e[A”:history-search-backward’
    bind ‘”\e[A”:history-search-backward’

    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.

    • 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.

    • Bruce Barrett

      Looks like that second line should have been:

      bind ‘”e[B”:history-search-forward’

      so you can use up *and down* arrows, as expected.

  • 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:

    $ ./prepare_reports [Enter]
    $ scp new_reports website:/path/to/reports [Enter]
    $ rake deploy website [Enter]
    [Up] [Up] [Up], prompt says:
    $ ./prepare_reports [CTRL+o]
    prompt says:
    $ scp new_reports website:/path/to/reports [CTRL+o]
    prompt says:
    $ rake deploy website [CTRL+o]
    prompt says:
    $ ./prepare_reports [CTRL+o]

    And so on. Quite nice!

  • Anon

    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:

  • suoranciata

    my fav bash shortcut is zsh 8)

  • 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”!

    • Bantuts

      Great tip! Thanks!

  • K

    For Vi[m] users, the following .inputrc makes life nicer:

    === 8><8 ===

  • Pingback: Inspiration round-up « Digital Marketing Blog by Soak Digital()

  • Pingback: Bash Shortcuts()

  • rod elias

    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.

  • 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:


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

  • 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.

    $ grep -H foo *.log

    • Scott Rowley

      I realize this was a year ago but you could do the following:

      $ grep -l foo *.log
      $ vim `!!`
      You would now be editing biz.log which contains foo

    • mykelalvis

      vim $( !! )

  • rod elias


    Are you sure?
    I tried that and it didn’t work out.

  • Pingback: Bash productivity tips « 0ddn1x: tricks with *nix()

  • 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.

    • 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.

        • Martin Larsen

          That doesn’t work. The problem is that when you return to the command line, bash will execute the command in question, whether it was altered or not. So, if you called up “rm -rf *” and open it with ctrl-x ctrl-e and think you can avoid the disaster by cancel editing, you are screwed! You have to delete the command, save and exit.

          • Andrei

            It works for me OK with :cq. But if I quit with :q! it will execute the command.

          • Martin Larsen

            Yes, that’s what I mean. So if you accidentally recall a disastrous command and think you can quit and be safe with :q! you are in trouble! Bash should not execute the command after return from the editor; Much better if you had to press Enter to execute.

          • Kassius

            This is quite absurd; would be impossible for bash to execute a command left with :q! because vim itself doesn’t saves it to a temporary file.

          • Patrick Bulteel

            Prepend the dissastrous command with #. So if you had rm -rf * you would have #rm -rf * and nothing would get executed.

            By the way, you get the same effect of ctrl-x, ctrl-e with “fc” – and it doesn’t stay in your history.

            (edited: to add the comment about fc.)

        • Florian Stichlberger

          With :cq vim returns a non-zero exit code which prevents the command execution – can be found in the vim help

          :cq[uit][!] Quit Vim with an error code, so that the compiler
          will not compile the same file again.
          WARNING: All changes in files are lost! Also when the
          [!] is not used. It works like “:qall!” :qall,
          except that Vim returns a non-zero exit code.

      • For anyone coming across this, I think also if you just delete the command in the editor and save it returns an empty command and so nothing gets run.

  • Pingback: BASH Shortcuts » Things and Stuff()

  • kalo

    On Mac OS X it is possible to remap the “esc” key to the “alt” key in!

    This has the advantage to keep the “alt” key pressed while pressing the “b” key repeatedly (as an example).


    Preferences > Settings > [profile] > Keyboard > enable “Use Option as meta key”


  • Pingback: OS X Terminal Tutorials()

  • I printed this out and keep it on my desk. Thanks a ton!

  • Pingback: Использование shortcuts в bash | Web Development()

  • Pingback: Bash Shortcuts You Should Know | Best Cheat Sheets()

  • j0lly

    Wow, you really opened my mind! I’ll share it in someway, it is really really interresting!

  • Bruno

    What? No undo in the bash command line handling? Ooooh this is so poor… If I edit a command line and type ctrl-W by mistake, is there a nice/quick way to recover from my mistake?

    Thanks for this great compilation.

    • In this specific case, ctrl+y will behave like an undo.

    • Dmitry

      Hi, Bruno!
      It’s not true, ofcourse!
      What you need is ctrl+x ctrl+u

    • j0n3

      ctrl + 7 or ctrl + _ should work

  • Very important information. Thanks for sharing

  • Did you miss Ctrl + L = Clear Screen
    And Ctrl + D = Exit Bash

    • nnsense

      Clarification, from The Bible -: CTRL+D – Delete the character at point. If point is at the beginning of the line, there are no characters in the line, and the last character typed was not bound to delete-char, then return EOF”. I find it very annoying since sometimes you use CTRL+D for other reasons and you may eventually close your own session, so I’ve disable it by setting “IGNOREEOF” in my bashrc.

  • Pingback: linkdump 2212013 |

  • I have a question!

    is Bash Bang commands belongs to emacs key bindings?

  • Pingback: Bash kısa yolları | Günlük()

  • CTRL + D – delete character under the cursor, or exit bash if user has not typed anything

  • Pingback: Bash Shortcuts | 90 Minute Indie()

  • phcostabh

    How come I have lived without it for so long? Thank you a lot.

  • Sandeep Nair

    Thanks buddy!

    Its a very useful piece of information

  • Pingback: Bash Killer Shortcuts | Linux Recipes()

  • auntchilada

    ctrl-O will discard the output until another ctrl-O is entered.

  • D.Baris Acar

    I would also add C-/ for undo in command line. Real saver for me…

  • Victotronics

    Execute the previous command but replacing “foo” with “bar”.

    Take the last command that contained “foo”, and do it with “bar” replacing foo throughout. Really, I have no idea what those last two characters mean.

    • Alexander Shishlev

      Kind of late, but put my 50 cents. Last two characters are to made changes in many places, if you’ll want to repeat

      cp foo foo.back
      with bar replacing foo, and skip last three characters (:g&) you’ll get

      “cp bar foo.back”


      “cp bar bar.back”.

      In fact it’s three different commands:

      !?foo? – to find last command in history with such substring, last ? need if you combine the commands with “:”. If you only need to repeat the last command, you can skip the last ?.

      s/foo/bar/ – search for the substring and replace it with another, but only once.

      g& – repeat search and replace for the whole string.

      Be aware, command like !?cp? will match both for cp and cpp, if cpp was executed last, !?cp? will match cpp, if you want to repeat cp after cpp, then you could use !?cp ?.

      This all was tested for Ubuntu 16.

      Oh, and don’t bother with testing if g will work without &, it won’t. Stick to the g&.

  • metafaniel

    My personal favorite is `sudo !!` I often forget to type sudo when needed. It’s like saying “I said run the command!!!!! DO IT NOW!!” hahaha

  • man readline

  • B.Max

    !* represent every arguments from the previous command aside from the #0 which is the command itself (You can get it by typing !#), it doesn’t remove any characters from the end.

    $ echo First second third
    First second third
    $ echo !*
    First second third

    n.b: you might see echo First second third before the actual output of the command, this is because bash (not sure about other shells), will echo the resulting command after parsing the special strings (like !!, !#, !:1, $?, …).

    !# and $? are also really useful as they respectively print the previous command (in the example above, echo !# would have echoed “echo”) and $? outputs the returned code (so 0 if successful, 1 if something went wrong, …) which is how you would usually see if something failed or not without having to re-type or encapsulate the command.

  • EddytheHat

    Sure I’m late to the party but I also like the !?blah feature to run a command where the pattern does not occur at the beginning of the line

  • Alan Dawkins

    I found some are also useful in vim, like ctrl+w. :D


    Great information, Definitely very helpful for everyone working in Linux.

    Thank you guys….