Command-Line Editing
If you type something wrong on a command line, the bash shell ensures that you don't have to
delete the entire line and start over. Likewise, you can recall a previous command line and change
the elements to make a new command.
By default, the bash shell uses command-line editing that is based on the emacs text editor. (Type
man emacs to read about it, if you care to.) If you are familiar with emacs, you probably already
know most of the keystrokes described here.
If you prefer the vi command for editing shell command lines, you can easily make that
happen. Add the line:
set -o vi
to the .bashrc file in your home directory. The next time you open a shell, you can use vi com-
mands (as described in the tutorial later in this chapter) to edit your command lines.
To do the editing, you can use a combination of control keys, meta keys, and arrow keys. For
example, Ctrl+F means to hold the Ctrl key and type f. Alt+F means to hold the Alt key and type f.
(Instead of the Alt key, your keyboard may use a Meta key or the Esc key. On a Windows keyboard,
you can use the Windows key.)
To try out a bit of command-line editing, type the following:
$ ls /usr/bin | sort -f | less
This command lists the contents of the
/usr/bin
directory, sorts the contents in alphabetical
order (regardless of case), and pipes the output to
less
. The
less
command displays the first
page of output, after which you can go through the rest of the output a line (press Enter) or a page
(press the spacebar) at a time (type q when you are done). Now, suppose you want to change
/usr/bin
to
/bin
. You can use the following steps to change the command:
1.
Press the up arrow to recall the line.
2.
Press Ctrl+A. This moves the cursor to the beginning of the command line.
3.
Press Ctrl+F or the right arrow (
) key. Repeat this command a few times to position the
cursor under the first slash (/).
4.
Press Ctrl+D. Type this command four times to delete
/usr
from the line.
5.
Press Enter. This executes the command line.
As you edit a command line, at any point you can type regular characters to add those characters
to the command line. The characters appear at the location of your cursor. You can use right (
)
and left (
) arrow keys to move the cursor from one end to the other on the command line. You
can also press the up (
) and down (
) arrow keys to step through previous commands in the his-
tory list to select a command line for editing. (See the discussion on command recall for details on
how to recall commands from the history list.)
TIP
TIP
49
Running Commands from the Shell
2