Bash

Материал из Ай да Linux Wiki
Перейти к навигации Перейти к поиску
Bash
Bash demo.png
Изображение bash и sh сессии
Автор Brian Fox
Первая версия 7, 1989; 34 years ago (1989-06-07)
Статус разработки Active
Написана на C
ОС Cross-platform
Платформа GNU
Язык English, multilingual (gettext)
Тип Unix shell
Лицензия GNU General Public License version 3
Website Bash GNU project home page

Bash — это акроним от Bourne-again-shell, «ещё-одна-командная-оболочка-Борна». Название — игра слов: Bourne-shell — одна из популярных разновидностей командной оболочки для UNIX (sh), автором которой является Стивен Борн (1978), усовершенствована в 1987 году Брайаном Фоксом. Фамилия Bourne (Борн) перекликается с английским словом born, означающим «родившийся», отсюда: рождённая-вновь-командная оболочка.

Bash - это POSIX shell написанный в рамках проекта GNU. Является самым распространенным командным интерпретатором и используется по умолчанию в подавляющем количестве дистрибутивов GNU/Linux.

История

Фокс начал разработку Bash 10 января 1988 года, после того как Ричард Столлман стал недоволен отсутствием прогресса в разработке. Фокс выпустил первую бета-версию bash 0,99 7 июня 1989 года и был главным разработчиком с середины 1992 по середину 1994 года, затем был уволен из FSF и его ответственность перешла на Чета Рамей.

Features

Синтаксис bash является расширенным вариантом синтаксиса Bourne shell`a. Подавляющее большинство скриптов sh могут выполняться bash`ем без изменений. Bash включает в себя идеи ksh и csh такие как история команд, редактор командной строки, переменные $RANDOM, $PPID и $(…). При использовании в качестве интерактивной оболочки и двойном нажатии клавиши tab происходит автоматическое дополнение команд, имен файлов и переменных.

Bash имеет много возможностей, которых не хватает в Bourne shell. Например, bash может выполнять вычисления с целыми числами без порождения внешних процессов. Bash упрощает перенаправление ввода/вывода способами, которые невозможны в традиционных шелах Борна. Например, Bash может перенаправить стандартный вывод (STDOUT) и стандартная ошибка (STDERR) используя оператор &>. Это проще напечатать, чем эквивалентная команда в Bourne Shell 'command > file 2>&1'. When using the 'function' keyword, Bash function declarations are not compatible with Bourne/Korn/POSIX scripts (the Korn shell has the same problem when using 'function'), but Bash accepts the same function declaration syntax as the Bourne and Korn shells, and is POSIX conformant. Due to these and other differences, Bash shell scripts are rarely runnable under the Bourne or Korn shell interpreters unless deliberately written with that compatibility in mind, which is becoming less common as Linux becomes more widespread. But in POSIX mode, Bash conformance with POSIX is nearly perfect.

Bash supports here documents just as the Bourne shell always has. However, since version 2.05b Bash can redirect standard input (stdin) from a "here string" using the <<< operator.

Bash 3.0 supports in-process regular expression matching using a syntax reminiscent of Perl.

Bash 4.0 supports associative arrays allowing faked support for multi-dimensional arrays, in a similar way to awk:

declare -A a         # declare an associative array 'a'
i=1; j=2             # initialize some indices
a[$i,$j]=5           # associate value "5" to key "$i,$j" (i.e. "1,2")
echo ${a[$i,$j]}     # print the stored value at key "$i,$j"

Brace expansion

Brace expansion, also called alternation, is a feature copied from the C shell that generates the set of alternative combinations. The generated results need not exist as files. The results of each expanded string are not sorted and left to right order is preserved:

echo a{p,c,d,b}e # ape ace ade abe
echo {a,b,c}{d,e,f} # ad ae af bd be bf cd ce cf

Brace expansions should not be used in portable shell scripts, because the Bourne shell will not produce the same output.

# A traditional shell does not produce the same output
echo a{p,c,d,b}e # a{p,c,d,b}e

When brace expansion is combined with wildcards, the braces are expanded first, then the resulting wildcards are substituted normally. Hence, a listing of JPEG and PNG images in the current directory could be obtained with:

ls *.{jpg,jpeg,png}    # expands to *.jpg *.jpeg *.png - after which,
                       # the wildcards are processed

Стартовые скрипты

When Bash starts, it executes the commands in a variety of different scripts.

When Bash is invoked as an interactive login shell, it first reads and executes commands from the file /etc/profile, if that file exists. After reading that file, it looks for ~/.bash_profile, ~/.bash_login, and ~/.profile, in that order, and reads and executes commands from the first one that exists and is readable.

When a login shell exits, Bash reads and executes commands from the file ~/.bash_logout, if it exists.

When an interactive shell that is not a login shell is started, Bash reads and executes commands from ~/.bashrc, if that file exists. This may be inhibited by using the --norc option. The --rcfile file option will force Bash to read and execute commands from file instead of ~/.bashrc.

Some versions of Unix have especially contorted system scripts for Bash which will effectively violate the documented script load order by loading scripts too early or attempting to combine Bash startup with the startup scripts for other shells in various ways.

Portability

Shell scripts written with Bash-specific features (bashisms) will not function on a system using the Bourne shell or one of its replacements, unless Bash is also installed and the script begins with a "shebang line" of #!/bin/bash interpreter directive instead of #!/bin/sh.

Keyboard shortcuts

The following shortcuts work when using default (Emacs) key bindings. Vi-bindings can be enabled by running set -o vi.

  • Tab  : Autocompletes from the cursor position.
  • Ctrl+a : moves the cursor to the line start (equivalent to the key Home).
  • Ctrl+e : (end) moves the cursor to the line end (equivalent to the key End).
  • Ctrl+p : (previous) recalls the prior command (equivalent to the key ).
  • Ctrl+n : (next) recalls the next command (equivalent to the key ).
  • Ctrl+r : (research) recalls the last command including the specified character(s). A second Ctrl+r recalls the next anterior command which corresponds to the research
  • Ctrl+s : Go back to the next more recent command of the research (beware to not execute it from a terminal because this command also launches its XOFF). If you changed that XOFF setting, use Ctrl+q to return.
  • Ctrl+o : executes the found command from research.
  • Ctrl+l : clears the screen content (equivalent to the command clear).
  • Ctrl+u : clears the line content before the cursor and copies it into the clipboard.
  • Ctrl+k : clears the line content after the cursor and copies it into the clipboard.
  • Ctrl+w : clears the word before the cursor and copies it into the clipboard.
  • Ctrl+y : (yank) adds the clipboard content from the cursor position.
  • Ctrl+d : sends an EOF marker, which (unless disabled by an option) closes the current shell (equivalent to the command exit). (Only if there is no text on the current line)
  • Ctrl+c : sends the signal SIGINT to the current task, which aborts and closes it.
  • Ctrl+z : sends the signal SIGTSTP to the current task, which suspends it. To execute it in background one can enter bg. To bring it back from background or suspension fg ['process name or job id'] (foreground) can be issued.
  • Ctrl+x Ctrl+x : (because x has a crossing shape) alternates the cursor with its old position.
  • Ctrl+x Ctrl+e : edits the current line in the $EDITOR program, or vi if undefined.
  • Alt+f : (forward) moves forward the cursor of one word.
  • Alt+b : (backward) moves backward the cursor of one word.
  • Alt+Del : cuts the word before the cursor.
  • Alt+d : cuts the word after the cursor.
  • Alt+u : capitalizes every character from the cursor's position to the end of the current word.
  • Alt+l : lowers the case of every character from the cursor's position to the end of the current word.
  • Alt+c : capitalizes the character under the cursor and moves to the end of the word.
  • Alt+r : cancels the changes and put back the line as it was in the history.

Комбинации клавиш

ctrl+u удалить все символы от курсора до начала строки

ctrl+k удалить все символы от курсора до конца строки

ctrl+w удалить слово перед курсором

ctrl+b переместить курсор на один символ влево

ctrl+f переместить курсор на один символ вправо

ctrl+t поменять местами символ слева от курсора и под курсором

ctrl+h удалить символ слева от курсора

ctrl+a переместить курсор в начало строки

ctrl+e переместить курсор в конец строки

ctrl+p предыдущая команда в истории bash

ctrl+n следующая команда в истории bash

ctrl+r реверсивный поиск команд в истории bash

ctrl+y вставляет последнюю удаленную с помощью ctrl+u или ctrl+k строку

ctrl+m выполнение команды, аналог [Enter]

ctrl+o выполняет команду, при этом оставляя ее в командной строке для дальнейшего использования.

ctrl+l очистить экран

ctrl+s стоп режим. Блокирует вывод на консоль. При этом все данные отображенные на экране остаются не измененными.

Tab+Tab выводит список команд. При наличии какого нибудь символа(-ов) выводит команды по введенным символам.

ctrl+q выход из стоп-режима.

ctrl+d выйти из терминала

ctrl+c отменить последнюю введенную команду

ctrl+x,ctrl+v показать версию bash

Ссылки

Bash