More efficient use of bash--shortcut keys under Linux

Source: Internet
Author: User
Tags control characters readline stdin

Under Linux, the status of Bash is negligible, and the daily management and operation of Linux is mostly done in bash, so in order to improve the productivity of Linux, it becomes the problem of how to use bash efficiently. While some of the special characters under the shell can be used to some extent to improve efficiency, the latter's historical expansion under Bash can also be much more efficient, but some of the shortcuts on bash are the simplest and most straightforward way to improve efficiency. This is the aim of this article!

Some instructions for shortcut keys:

    1. C = CTL = Ctrl = CONTROL: This key refers to the CTRL key on the PC keyboard
    2. M = alt: This key is the ALT key on the PC keyboard, if you do not have this key on the keyboard, you can try to use the ESC key instead
    3. S = Shift: This key is the SHIFT key on the PC
    4. E = ESC: This key is the ESC key on the PC keyboard, which is usually in the upper left corner of the keyboard
    5. DEL = Backspace: This key is the Backspace key on the PC keyboard, typically located in the upper right corner of the main keyboard area
    6. In the text "[]" surrounded by the content of the shortcut key, "-" on both sides of the content is to hold down the left button, and then press the right button to obtain, "," the contents of the comma on both sides of the first press the left button, release and then press the right button. such as: [C-v] is to indicate that the CTRL key is pressed, do not release, and then press the V key.
    7. By default, the form of shortcut keys is: <ctrl | Alt | Esc>-[shift-]<char>. This is the beginning of one of the Ctrl,alt,esc, an underscore, a Shift, an underscore, and a character. Where the shift and "-" in brackets are sometimes omitted.
    8. By default, the shortcut key is only the last character, and the other key values are function keys
    9. appears [C-?] This type of shortcut is due to "?" is a character that needs to be obtained by using the SHIFT key, so this type of shortcut is used by default [c-s-?]

Note that in bash, shortcut keys may be written in octal or hexadecimal form (following the escape character); The shortcut keys in the script file do not always work. In addition, shortcut keys have a rule,Ctrl starts with the shortcut keys are generally for the character, and alt the beginning of the shortcut key is generally for the word .

Under Bash, if you are using a shell script file, the shortcut key does not always appear to have a different performance for the same shortcut key, which is usually caused by the different modes that bash is in, and you can set adjust the pattern by command:

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

This is the option for bash, you can set it according to the situation, this article uses the Emacs mode.

shortcut Keys Shortcut key Description
C-a Move the cursor to the beginning of the line (under command)
C-b BACKSPACE (non-destructive), this just moves the cursor position back one position.
C-c Interrupt. End a foreground job.
C-d Exit from a shell (similar to exit). " EOF (End of File: End of file). It is also used to indicate the end of standard input (stdin). When you enter text in the console or Xterm window, c-d deletes the character under the cursor. If no characters exist, c-d logs out of the session. In a xterm window, the effect of closing this window is generated.
C-e Move the cursor to the end of the line (command line)
C-f Move the cursor forward one character (command line)
C-g BEL. On some older printer terminals, this raises a bell. May be a beep on the xterm terminal.
H Erase (Rubout) (destructive backspace). While the cursor is moving back, erase one character before the cursor.
Code
123456789101112131415161718192021222324 #!/bin/bash## 可以尝试下下面的代码## C-H的表现也许和你想象的不一样## 本例来自Advanced Bash-Scripting Guide## 注意:因为中文原因,下面的^位置可能会出现漂移a="^H^H"echo "abcdef"echoecho -n "abcdef$a "# abcd f#  末尾有个空格     ^              ^  两次C-H的结果echoecho -n "abcdef$a"# abcdef#  末尾没有空格                        ^ 显示效果是没有按C-H?(为什么?).                          # 这个结果和我们预期的不一致.echoechorubout="^H^H^H^H^H" # 5个C-H.## 来吧,让我们看看真相:echo -n "12345678"sleep 2echo -n "$rubout"sleep 2## 现在,你知道真相了么?
C-i Horizontal tab.
C-j New lines (line feed) and start at the beginning. In the script, it may also be represented as an octal form (' \012 ') or hexadecimal (' \x0a ').
c-k Vertical tab (Vertical tab.). When you enter text in the console or Xterm window, C-k removes all characters from the cursor to the end of the line. In the script, ctrl-k may have different behavior, the following example gives its different behavior:
code
123456789101112 #!/bin/bash ## A c-k vertical tab example  var=$ ' \x0abottom line\x0btop line\x0a ' ## Direct output echo ## use Col to filter control characters echo "$var" | Col  ## the above display will be different  exit 0
C-l Skip the paper, change the page (formfeed), clear the screen. Clear the terminal screen. On the terminal, this command acts like a clear command. But when this command is sent to the printer, Ctrl-l jumps directly to the end of the paper (Paper sheet).
C-m Enter (carriage return).
C-n Erases a line of text recalled from the history buffer (at the command line). If the current input is selected in the history, this is from this history, not pressed once, is closer to a command
C-o Generate a new Line (command line)
C-p Recall the last Command (command line) from the history buffer. The order of this shortcut was recalled by from near, that is, by pressing once, recalling the previous command, and then pressing it again, the previous command was recalled, and the c-n is starting with the current input, but the two commands operate just the opposite, and the c-n is starting from the beginning by far and near (if the beginning is the historical command).
C-q Resume (XON). Restore/Thaw, this command is used to restore the terminal's stdin, see C-s
C-r Backtracking search (backwards search) text in the history buffer (command line), note: After pressing, the prompt becomes (reverse-i-search) ': The entered search content appears in single quotation marks, and the most recent matching history command appears after the colon
C-s Suspend (XOFF), hangs, this is the stdin that freezes the terminal. To recover you can press C-Q.
C-t Swaps the character contents of the cursor position with the previous position of the cursor (command line). For example echo $var; , assuming that the cursor is on a, then when C-T is pressed, V and a will swap positions.
C-u Erases all character content from the cursor position to the beginning of the line. Under certain settings, C-u does not remove input from the entire row with the cursor position as a reference.
D-1 When you enter text, you can insert a control character after you press C-V. For example: As echo -e ‘\x0a‘; with echo <C-V><C-J>; these two effects. This feature works well in a text editor.
C-w When you type text in the console or in a xterm window, C-w removes the contents from the first white space character that is back at the cursor. In some settings, C-w removes the character from the cursor (back) to the first non-literal and number.
C-x In some word-processing programs, this control character will cut the highlighted text and copy it to the Clipboard.
C-y Paste the previously cleared text back (primarily for c-u or c-w).
C-z Pauses a foreground job, and also acts as a replacement in some text handlers, and as EOF (End-of-file) characters in the Msdos file system.
C-\ Exit. Similar to c-c, you may dump a "core" file into your working directory (this file may not work for you)
c-/ Undo action, Undo.
C-_ Undo Action
C-xx Switch between the beginning of the line and the cursor two positions, here are two "X" characters
M-b The cursor jumps back one word, and the word is bounded by non-letters (jumping to the beginning of the word where the cursor is currently located).
M-f The cursor jumps forward one word (moves to the end of the word where the cursor is located)
M-d Delete all content at the end of the word where the cursor is located (or delete the entire word if the cursor is at the beginning of the word)
M-del Del is the BACKSPACE key, which deletes everything from the position of the cursor to the beginning of the word.
M-c Capitalize the letter at the position of the cursor (if the cursor is in or before the beginning of a word, capitalize the first letter of the word)
M-u Capitalize all letters in the position of the cursor to the ending
M-l Turn all the letters from the cursor position to the ending to lowercase
M-r Cancels all changes and restores the current row to its original state in the history (provided the current command is from the history, and if it is entered manually, the row is emptied).
M-t When words are present on both sides of the cursor, swap the positions of the words on both sides of the cursor. such as: abc <M-T>bcdbcd abc
M-. Use the last word of the previous command (the command itself is also a word, see the word indicator concept in the Bang command in the following article)
M-_ With M-.
M-no. m+ number, this number can be positive or negative, this key alone has no effect, must be followed by other content, if the following is a character, then the number of repetitions, such as: [m-10,k] The cursor position will be inserted 10 k characters (negative value in this case is invalid); The number affects the execution of subsequent commands, such as: [M--10,c-d] performs 10 operations in the direction of the opposite (negative) direction of the c-d default.
m-< Moves to the first line of the history Record command.
M-> Moves to the last line of history, which is currently being entered (null if no input is present)
M-p Search forward from the current line, and it is necessary to move to up, and use non-incremental search to find the user-supplied string when moving.
M-n Searches backward from the current line and, if necessary, moves to "down", using a non-incremental search to find the user-supplied string.
M-c-y Inserts the first parameter of the previous command (usually the second word in the previous line) on the flag point. If there is a parameter n, insert the nth Word of the previous command (the word number from the previous line starts with 0, see history extension). A negative argument inserts the nth word that starts at the end of the previous command. The parameter n is passed through m-no, such as: [M-0,m-c-y] Inserts the NO. 0 Word of the previous command (the command itself).
M-y Polls to the delete ring and copies the new top text. Use this command only after Yank[c-y]] or yank-pop[m-y].
M-? Lists the entries that can be complete before the Mark Point
m-* Put possible-completions[m-?] The command can generate all the text entries that are inserted before the flag point.
m-/ An attempt was made to complete the file name of the text before the flag point. [c-x,/] treats the text before the marker as a file name and lists the entries that can be complete.
m-~ Use the text in front of the logo as the user name and try to complete the completion. [c-x,~] Lists the entries that can be used as the user name complement flag point.
m-$ Think of the text before the mark point as a shell variable and try to complete the completion. [c-x,$] Lists the entries that can be used as the variable complement flag point.
[Email protected] The text before the mark Point is treated as a hostname and attempted to complete. [c-x,@] Lists the entries that can be used as the host complement flag point.
m-! The text before the mark Point is treated as a command name and attempted to complete. The command name completion is followed by the alias, reserved word, shell function, shell internal command, and finally the executable file name. [c-x,!] The text in front of the mark Point is listed as the command name and a complete entry is made.
M-tab Compare the text in front of the mark point to the text in the history to find a match and try to complete the completion.
m-{ Complete the file name, and put the list of entries that can be complete between the braces so that the shell can use it.

Under Bash, if you can use the shortcut keys properly, the operation of the Linux system will become very fast, for example, when we use the cat create a file, we can use the shortcut key [c-d]:

Code
12345678910 ## 不用快捷键cat>>/tmp/test<<_EOF##这里是内容##最后我们要在新行里面输入_EOF##cat见到_EOF才会将内容写到文件中 ##使用快捷键cat>>/tmp/test##这里输入内容##输入完毕之后,直接[C-D]结束

Sometimes we need to create a file and then manipulate the file:

Code
12345678 touch/tmp/a-test-file-from-blog.useasp.net ## 不使用快捷键,文件名要重新输入chmod u+x /tmp/a-test-file-from-blog.useasp.net ##使用快捷键chmodu+x <M-.>## 快捷键[M-.]自动会将上面的最后一个参数附加

What, is there more efficiency?

Of course, bash shortcut keys only in the continuous use, to achieve real efficiency, in the beginning even to use that shortcut to think about a half-day situation, high efficiency is very difficult-but the knife does not mistakenly cut timber workers, the upfront investment is worthwhile.

If you want your bash to be a little different, you can customize the shortcut by yourself, using the bind command, and the shortcut keys in Bash are actually readline to provide, so the settings for the shortcut here are actually configuration ReadLine, There are two kinds of shortcut keys in ReadLine, one is the function shortcut key inside the ReadLine, the other is the execution shell command, the setting time is slightly different:

code
123 4567891011121314 # #查看Readline中可以使用的函数名称 bind-l # #查看当前绑定的案件配置与其对应的功能 bind- v # #已经绑定的快捷键 bind-p  # #绑定自定义执行命令shell命令的快捷键 bind-x  "\c-x\c-l": Ls-al ' ## bind, press [C-x,c-l] to execute ls-al  ## bind built-in function function bind  "\c-x" :backword-delte-char # #这个是这行Readline库中的函数backword-delte-char

This setting is only valid for the current session, and once the session is lost, the shortcut keys for the setting are lost, so we need to write the shortcut key's configuration to the file in order for the shortcut key to be permanently valid. In the Linux system, can permanently save the shortcut key place has two, the global and user's profile, the global is /etc/inputrc , and the user is in the user's root directory ~/.inputrc , the global will affect all users, and the user root directory will only affect the corresponding users. The inputrc file might look like this:

Code
12345678910111213141516171819202122232425262728293031 ## 本例来自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

Description

    1. In the configuration file, \c represents ctrl,\m on behalf of Alt,\e Escape[esc],\\ is a backslash [\],\ ' is a single quote, \ ' is a double quote;
      \c-    control prefix\m-    Meta prefix\e an     escape character\\     backslash\ "     literal", a double quote \ '     literal ', a single quote
    2. If you want to see a character sequence of a function key can be achieved by [c-v], or enter cat back, enter the editor, press the shortcut key directly
    3. Characters may be represented in the configuration file using octal or hexadecimal notation.

If we set up the appropriate shortcut for the commonly used operation, perhaps the previous need to Balabala knock half command, you can do a shortcut key, which will undoubtedly greatly improve our efficiency! Shortcut Key Bar, Sao year!

More efficient use of bash--shortcut keys under Linux

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.