CLI Tricks: Navigating Around the Prompt

It’s not uncommon to need to make changes to a command after entering it in the command prompt. For example, perhaps you need to reuse a command from the history but with a small change or perhaps you need to fix a typo.

Luckily, Unix command prompts support both Emacs (default) and Vi(m) key bindings for quickly arriving at the section you need to make small edits.

Let’s take an example where you want to download a light AWS stemcell (~6 KB):

curl -L -J -O https://bosh.io/d/stemcell/bosh-aws-xen-ubuntu-trusty-go_agent

There is a typo in the above line: the path should include d/stemcells not d/stemcell. Of course this typo is awkwardly placed, so what’s the best way to fix it?

Method E: Emacs Bindings

The key bindings of interest here are ^a, ^e, esc+f, and esc+b where ^ represents the ctrl key. Try the following:

  1. Copy the curl statement as-is, typo and all, into your command prompt
  2. Enter ^a to go to the beginning of the line
  3. Enter esc+f until you reach the end of the world stemcell (should be 9 times).
  4. Type in the s so stemcell becomes stemcells

At this point you can either enter ^e to go to the end of the line or Enter/Return to execute the command. Although we didn’t use it in this example, just like esc+f goes forward a word at a time, esc+b goes backward.

Caveat: make sure you don’t just hold down the esc key and keep hitting b or f. If you do, you’ll just typing b’s and f’s. You must hit esc+b or esc+b each time you want to move backward/forward a word.

Method V: Vi(m) Bindings

Since Emacs is default, in order to switch into Vi mode first run:

set -o vi

As with the previous exercise, copy the curl command into terminal with the typo. The key bindings of interest here are: ^, $, b, e, and w.

  1. Copy the curl statement as-is, typo and all, into your command prompt
  2. Hit esc to go into command mode
  3. Enter ^ to go to the beginning of the line
  4. Enter 16e, which will place the cursor at the end of the world stemcell.
  5. Hit a to enter insert mode next to the last l in stemcell
  6. Type in the s so stemcell becomes stemcells

At this point you can either use esc (to go back into command mode) and enter $ to go to the end of the line or Enter/Return to execute the command. Note that the command can be run in either command or insert mode.

If you wish to return to Emacs mode at any time, enter:

set -o emacs

Spread the word

twitter icon facebook icon linkedin icon