Under Linux, the importance of Bash cannot be ignored. Daily Linux management and operations are basically carried out in Bash. Therefore, to improve work efficiency under Linux, the question naturally becomes how to use Bash efficiently. Using some shortcuts in Bash is the simplest and most direct way to improve efficiency. This article is exactly aimed at that goal!

Bash 快捷键大全

Some explanations about the shortcuts:

  1. CTRL=C: This key refers to the Ctrl key on a PC keyboard.
  2. ALT=M: This key is the ALT key on a PC keyboard. If your keyboard does not have this key, you can try using the ESC key instead.
  3. SHIFT=S: This key is the Shift key on a PC.
  4. ESC=E: This key is the ESC key on a PC keyboard, generally located in the upper-left corner of the keyboard.
  5. BACKSPACE=DEL: This key is the Backspace key on a PC keyboard, generally located in the upper-right corner of the main key area.
  6. In this article, the content enclosed in "[]" is the shortcut key content. On both sides of "-" means to hold down the left key, then press the right key. On both sides of "," (comma) means to press the left key first, release it, then press the right key. For example, [CTRL-v] means to press the Ctrl key, do not release it, and then press the v key.
  7. By default, the composition format of a shortcut is: <CTRL | ALT | ESC >-[SHIFT-]<char>. That is, it starts with one of Ctrl, Alt, Esc, followed by a hyphen, Shift, a hyphen, and a character. Among them, the Shift and "-" inside the brackets can sometimes be omitted.
  8. By default, only the last key of a shortcut is a character; the other key values are all function keys.
  9. For shortcuts like [CTRL-?], since "?" is a character that requires the Shift key to be typed, such shortcuts default to [CTRL-SHIFT-?].

Note that in Bash, shortcuts may be written in octal or hexadecimal form (following the escape character); shortcuts in script files do not always work. In addition, shortcuts follow a pattern:Shortcuts starting with Ctrl are generally for characters, while shortcuts starting with Alt are generally for words.。

Under Bash, if you are using a shell script file, the shortcuts may not be the same. Sometimes the same shortcut may behave differently. This is generally caused by Bash being in different modes. You can adjust the mode with the set command:

set -o emacs
##切到emacs模式
set -o vi
##切到vi模式
set -o
## 查看当前选项的设置状态

This is Bash's option setting; you can configure it according to the specific situation. This article uses the emacs mode.

Shortcut Shortcut description
CTRL-A Move the cursor to the beginning of the line (on the command line).
CTRL-B Backspace (non-destructive). This only moves the cursor position back one space.
CTRL-C Interrupt, terminate a foreground job.
CTRL-D "EOF" (end of file). It is used to indicate the end of standard input (stdin). When entering text in a console or xterm window, CTRL-D deletes the character under the cursor.

Exit from a shell (similar to exit). If no characters are present, CTRL-D will log out of the session. In an xterm window, this will have the effect of closing the window.

CTRL-E Move the cursor to the end of the line (on the command line).
CTRL-F Move the cursor forward one character (on the command line).
CTRL-G BEL. On some old printer terminals, this causes a bell to ring. On xterm terminals, it may be a beep.
CTRL-H Erase (Rubout) (destructive backspace). While the cursor moves backward, it simultaneously erases the character before the cursor.
CTRL-I Horizontal tab.
CTRL-J New line (line feed and carriage return to the beginning of the line). In scripts, it may also be represented in octal form ('/012') or hexadecimal form ('/x0a').
CTRL-K Vertical tab. When entering text in a console or xterm window, CTRL-K deletes all characters from the cursor position to the end of the line.

In scripts, it may also be represented in octal form ('/013') or hexadecimal form ('/x0b'). In scripts, CTRL-K may behave differently. The following example shows the different behavior:

#!/bin/bash
## 一个CTRL-K垂直制表符的例子

var=$'/x0aBottom Line/x0bTop line/x0a'
## 直接输出
echo "$var"
## 使用col来过滤控制字符
echo "$var" | col

## 上面的显示将会不一样

exit 0
CTRL-L Form feed, page feed, clear screen.

Clear the terminal screen. On a terminal, this command works the same as the clear command. But when this command is sent to a printer, Ctrl-L directly jumps to the end of the paper sheet.

CTRL-M Carriage return.
CTRL-N Erase a line of text recalled from the history buffer (on the command line). If the current input is selected from the history, starting from that history entry, each press gives a more recent command.
CTRL-O Produce a new line (on the command line).
CTRL-P Recall the previous command from the history buffer (on the command line). This shortcut recalls commands in order from most recent to oldest; that is, pressing once recalls the previous command, and pressing again recalls the command before that. Both this and CTRL-N start from the current input, but the two commands operate in exactly opposite directions: CTRL-N goes from the starting point from oldest to most recent (if the starting point is a historical command).
CTRL-Q Resume (XON). Resume/unfreeze. This command is used to restore the terminal's stdin; see CTRL-S.
CTRL-R Backward search through the text in the history buffer (on the command line). Note: after pressing it, the prompt becomes `(reverse-i-search)`: the entered search text appears within single quotes, and the most recent best-matching history command appears after the colon.
CTRL-S Suspend (XOFF), pause. This freezes the terminal's stdin. To resume, press CTRL-Q.
CTRL-T Swap the character at the cursor position with the character one position before the cursor (on the command line). For example: `echo $var;`, suppose the cursor is on `a`, then after pressing C-T, `v` and `a` will swap positions: `echo $avr;`.
CTRL-U Erase all characters from the cursor position to the beginning of the line. In some settings, CTRL-U deletes the entire input line regardless of the cursor position.
CTRL-V When entering text, after pressing C-V, you can insert control characters. For example: `echo -e '/x0a';` and `echo <CTRL-V><CTRL-J>;` these two have the same effect. This feature is very useful in text editors.
CTRL-W When typing text in a console or an xterm window, CTRL-W deletes the content from the cursor position backward to the first whitespace character. In some settings, CTRL-W deletes characters from the cursor backward to the first character that is not a letter or digit.
CTRL-X In some word processing programs, this control character will cut the highlighted text and copy it to the clipboard.
CTRL-Y Paste back text that was previously cleared (mainly for CTRL-U or CTRL-W).
CTRL-Z Suspend a foreground job; in some text processing programs it is also used as a replace operation; in the MSDOS file system it serves as the EOF (End-of-file) character.
CTRL-/ Exit. Similar to CTRL-C, it may also dump a "core" file to your working directory (this file may be useless to you).
CTRL-/ Undo operation.
CTRL-_ Undo operation.
CTRL-xx Toggle between the beginning of the line and the cursor position; here there are two "x" characters.
ALT-B The cursor jumps backward one word, with words delimited by non-letter characters (jumps to the beginning of the current word at the cursor).
ALT-F The cursor jumps forward one word (moves to the end of the current word at the cursor).
ALT-D Delete all content from the cursor position to the end of the current word (if the cursor is at the beginning of the word, delete the entire word).
ALT-BASKSPACE Delete all content from the cursor position to the beginning of the word.
ALT-C Convert the letter at the cursor position to uppercase (if the cursor is at or before the start of a word, capitalize the first letter of the word).
ALT-U Convert all letters from the cursor position to the end of the word to uppercase.
ALT-L Convert all letters from the cursor position to the end of the word to lowercase.
ALT-R Cancel all changes and restore the current line to its original state in the history (provided that the current command came from the history; if entered manually, it will clear the line).
ALT-T When there are words on both sides of the cursor, swap the positions of the words on both sides. For example: `abc <ALT-T>bcd -> bcd abc`
ALT-. Use the last word of the previous command (the command itself is also considered a word; see the word indicator concept in the Bang commands section of the next article).
ALT-_ Same as ALT-.
ALT-number This numeric value can be positive or negative. This key alone has no effect; it must be followed by other content. If followed by a character, it indicates the number of repetitions. For example: [ALT-10,k] inserts 10 'k' characters at the cursor position (negative values are invalid in this case); if followed by a command, the number affects the execution result of the subsequent command. For example: [ALT--10,CTRL-D] executes the operation 10 times in the direction opposite to CTRL-D's default direction (negative).
ALT-< Move to the first command in the history.
ALT-> Move to the last line in the history, i.e., the line currently being input (empty if there is no input).
ALT-P Search forward starting from the current line, moving "up" if necessary; while moving, use non-incremental search to find the user-provided string.
ALT-N Search forward from the current line, moving "down" if necessary. When moving, use non-incremental search to find the user-supplied string.
ALT-CTRL-Y Insert the first argument of the previous command (usually the second word of the previous line) at the point. If argument n is given, insert the nth word of the previous command (word numbering starts from 0; see History Expansion). A negative argument inserts the nth word from the end of the previous command. The argument n is passed via M-No., e.g., [ALT-0, ALT-CTRL-Y] inserts the 0th word of the previous command (the command itself).
ALT-Y Rotate to the kill ring and copy the new top text. This command can only be used after yank [CTRL-Y] or yank-pop [M-Y].
ALT-? List the possible completions of the text before the point.
ALT-* Insert before the point all text entries that the possible-completions [ALT-?] command can generate.
ALT-/ Attempt filename completion on the text before the point. [CTRL-X,/] treats the text before the point as a filename and lists possible completions.
ALT-~ Treat the text before the point as a username and attempt completion. [CTRL-X,~] lists possible completions for the text before the point as usernames.
ALT-$ Treat the text before the point as a Shell variable and attempt completion. [CTRL-X,$] lists possible completions for the text before the point as variables.
ALT-@ Treat the text before the point as a hostname and attempt completion. [CTRL-X,@] lists possible completions for the text before the point as hostnames.
ALT-! Treat the text before the point as a command name and attempt completion. When performing command name completion, aliases, reserved words, Shell functions, shell builtins, and finally executable filenames are used in turn. [CTRL-X,!] treats the text before the point as a command name and lists possible completions.
ALT-TAB Compare the text before the point with text in the history list to find matches and attempt completion.
ALT-{ Perform filename completion, placing the list of possible completions between braces so that the shell can use it.

Under Bash, if you can use shortcuts properly, operations on a Linux system become very quick. For example, when we use cat to create a file, we can use the shortcut [CTRL-D]:

## 不用快捷键
cat >>/tmp/test<<_EOF
##这里是内容
##最后我们要在新行里面输入_EOF
##cat见到_EOF才会将内容写到文件中

##使用快捷键
cat >>/tmp/test
##这里输入内容
##输入完毕之后,直接[CTRL-D]结束

Sometimes we need to create a file and then operate on it:

touch /tmp/a-test-file-from-blog.useasp.net

## 不使用快捷键,文件名要重新输入
chmod u+x /tmp/a-test-file-from-blog.useasp.net

##使用快捷键
chmod u+x <ALT-.>
## 快捷键[M-.]自动会将上面的最后一个参数附加

How about that? Isn't it more efficient?

Of course, Bash shortcuts can only achieve true efficiency through constant use. At first, when you have to think for a long time about which shortcut to use, being efficient is hard—but sharpening the axe won't delay the woodcutting, and the initial investment is worthwhile.

If you want your Bash to be a bit different, you can also customize shortcuts yourself by using the bind command. The shortcuts in Bash are actually provided by Readline; therefore, setting shortcuts here is actually configuring Readline. There are two types of shortcuts in Readline: one is Readline's internal function shortcuts, and the other executes Shell commands. They are slightly different when setting them up:

##查看Readline中可以使用的函数名称
bind -l
##查看当前绑定的案件配置与其对应的功能
bind -v
##已经绑定的快捷键
bind -p

##绑定自定义执行命令shell命令的快捷键
bind -x '"/C-x/C-l":ls -al'
## 绑定后,按[C-x,C-L]就能执行ls -al

## 绑定内置函数功能
bind "/C-x":backword-delte-char
##这个是这行Readline库中的函数backword-delte-char

This setting is only valid for the current session. Once the session is lost, shortcuts set this way are lost. In order to make the shortcuts permanent, we need to write the shortcut configuration into a file. In Linux, there are two places to permanently save shortcuts: the global and user configuration files. The global one is /etc/inputrc, and the user one is ~/.inputrc in the user's home directory. The global one affects all users, while the one in the user's home directory only affects the corresponding user. An example inputrc file looks roughly like this:

## 本例来自CentOS6.4的默认配置文件
$if mode=emacs

# for linux console and RH/Debian xterm
"/e[1~": beginning-of-line
"/e[4~": end-of-line
# commented out keymappings for pgup/pgdown to reach begin/end of history
#"/e[5~": beginning-of-history
#"/e[6~": end-of-history
"/e[5~": history-search-backward
"/e[6~": history-search-forward
"/e[3~": delete-char
"/e[2~": quoted-insert
"/e[5C": forward-word
"/e[5D": backward-word
"/e[1;5C": forward-word
"/e[1;5D": backward-word

# for rxvt
"/e[8~": end-of-line
"/eOc": forward-word
"/eOd": backward-word

# for non RH/Debian xterm, can't hurt for RH/DEbian xterm
"/eOH": beginning-of-line
"/eOF": end-of-line

# for freebsd console
"/e[H": beginning-of-line
"/e[F": end-of-line
$endif

Notes:

  1. In the configuration file, /C represents CTRL, /M represents ALT, /e represents ESC, // is the backslash /, /' is the single quote, and /" is the double quote.
    /C-    control prefix
    /M-    meta prefix
    /e     an escape character
    //     backslash
    /"     literal ", a double quote
    /’     literal ’, a single quote
    
  2. To view the character sequence of a function key, you can use [CTRL-V], or type cat and press Enter to enter editing, then press the shortcut directly.
  3. The configuration file may use octal or hexadecimal to represent characters.

If we set appropriate shortcuts for common operations, commands that previously required a lot of typing can be done with just one shortcut. This will undoubtedly greatly improve our work efficiency! Use shortcuts, young man!

Source: http://www.codeceo.com/article/bash-shortcut.html