Bash: различия между версиями

Материал из Ай да Linux Wiki
Перейти к навигации Перейти к поиску
м
 
(не показано 10 промежуточных версий этого же участника)
Строка 3: Строка 3:
 
| logo                  =
 
| logo                  =
 
| screenshot            = [[Image:Bash demo.png|250px]]
 
| screenshot            = [[Image:Bash demo.png|250px]]
| caption                = Screenshot of Bash and [[Bourne shell|sh]] sessions demonstrating some features
+
| caption                = Изображение bash и sh сессии
| author                = [[Brian Fox (computer programmer)|Brian Fox]]
+
| author                = Brian Fox
 
| released              = {{start date and age|1989|6|7}}
 
| released              = {{start date and age|1989|6|7}}
 
| frequently updated    = yes
 
| frequently updated    = yes
| programming language  = [[C (programming language)|C]]
+
| programming language  =
| operating system      = [[Cross-platform]]
+
| operating system      = Cross-platform
| platform              = [[GNU]]
+
| platform              = GNU
| language              = English, multilingual ([[gettext]])
+
| language              = English, multilingual
 
| status                = Active
 
| status                = Active
| genre                  = [[Unix shell]]
+
| genre                  = Unix shell
| source model          = [[Free software]]
+
| source model          = Free software
| license                = [[GPLv3|GNU General Public License version 3]]
+
| license                = GPLv3
 
| website                = [http://www.gnu.org/software/bash/ Bash GNU project home page]
 
| website                = [http://www.gnu.org/software/bash/ Bash GNU project home page]
 
}}
 
}}
  
'''Bash''' is a [[Unix shell]] written by [[Brian Fox (computer programmer)|Brian Fox]] for the [[GNU Project]]. The name is an [[acronym]], a [[pun]] and descriptive.  As an acronym, it stands for '''''B'''ourne-'''a'''gain '''sh'''ell'', referring to its initial conception as a [[free software]] replacement for the [[Bourne shell]] (sh). The name is also descriptive of what it did, ''bashing together'' the features of sh, [[C shell|csh]] and [[Korn shell|ksh]].
+
'''Bash''' - это ''POSIX shell'' написанный в рамках проекта GNU. Является самым распространенным командным интерпретатором, используется по умолчанию в подавляющем количестве дистрибутивов GNU/Linux.
  
Bash is a [[POSIX]] shell with a number of extensions. It is the shell for the [[GNU operating system]] from the GNU Project. It can be run on most [[Unix-like]] operating systems. It is the default shell on most systems built on top of the [[Linux kernel]] as well as on [[Mac OS X]] and [[Darwin (operating system)|Darwin]]. It has also been ported to [[Microsoft Windows]] using Subsystem for UNIX-based Applications (SUA), or the POSIX emulation provided by [[Cygwin]] and [[MinGW|MSYS]]. It has been ported to [[DOS]] by the [[DJGPP]] project and to [[Novell NetWare]].
+
'''Bash''' — это акроним от ''Bourne-again-shell'', «ещё-одна-командная-оболочка-Борна». Название — игра слов: Bourne-shell — одна из популярных разновидностей командной оболочки для UNIX (sh), автором которой является Стивен Борн (1978), усовершенствована в 1987 году Брайаном Фоксом. Фамилия Bourne (Борн) перекликается с английским словом born, означающим «родившийся», отсюда: рождённая-вновь-командная оболочка.
  
== History ==
+
==Особенности==
 +
Синтаксис bash является расширенным вариантом синтаксиса Bourne shell (часто просто sh по имени исполняемого файла). Подавляющее большинство скриптов sh могут выполняться bash`ем без изменений. Bash включает в себя идеи ksh и csh такие как история команд, редактор командной строки, переменные <tt>$RANDOM</tt>, <tt>$PPID</tt> и <tt>$(…)</tt>. При использовании в качестве интерактивной оболочки и двойном нажатии клавиши tab происходит автоматическое дополнение команд, имен файлов и переменных.
  
Fox began [[Computer programming|coding]] Bash on January 10, 1988 after [[Richard Stallman]] became dissatisfied with the lack of progress being made by a prior developer. Stallman and the [[Free Software Foundation]] (FSF) considered a free shell that could run existing sh scripts so strategic to a completely free system built from BSD and GNU code that this was one of the few projects they funded themselves, with Fox undertaking the work as an employee of FSF. Fox  released Bash as a beta, version .99, on June 7, 1989 and remained the primary maintainer until sometime between mid-1992 and mid-1994, when he was laid off from FSF and his responsibility was transitioned to another early contributor, Chet Ramey.
+
Bash имеет много возможностей, которых не хватает в Bourne shell. Например, bash может выполнять вычисления с целыми числами без порождения внешних процессов. Bash упрощает перенаправление ввода/вывода способами, которые невозможны в традиционных шелах Борна. Например, Bash может перенаправить стандартный вывод (STDOUT) и  стандартная ошибка (STDERR) используя оператор <tt>&></tt>. Это проще напечатать, чем эквивалентная команда в  Bourne Shell.
 +
<source lang="bash">command > file 2>&1</source>
  
==Features==
+
При использовании функций (function) bash не совместим с Bourne/Korn/POSIX шелами, но понимает их синтаксис. В силу этих и других различий, bash скрипты редко работоспособной под sh и ksh, если намеренно написаны с совместимостью. Но в режиме POSIX, соответствие POSIX является почти идеальным.
  
The Bash [[command (computing)|command]] syntax is a [[superset]] of the Bourne shell command syntax. The vast majority of Bourne shell scripts can be executed by Bash without modification, with the exception of Bourne shell scripts stumbling into fringe syntax behavior interpreted differently in Bash or attempting to run a system command matching a newer Bash builtin, etc. Bash command syntax includes ideas drawn from the [[Korn shell]] (ksh) and the [[C shell]] (csh) such as command line editing, [[command history]], the directory stack, the <tt>$RANDOM</tt> and <tt>$PPID</tt> variables, and POSIX [[command substitution]] syntax <tt>$(…)</tt>. When used as an interactive command shell and pressing the [[tab key]], Bash automatically uses [[command line completion]] to match partly typed program names, filenames and variable names.
+
С версии 2.05b bash может перенаправлять стандартный ввод (stdinиспользуя оператор <tt>'''<'''</tt>.
  
Bash's syntax has many extensions which the Bourne shell lacks. Bash can perform integer calculations without spawning external processes, unlike the Bourne shell. Bash uses the <tt>((…))</tt> command and the <tt>$((…))</tt> variable syntax for this purpose. Bash syntax simplifies [[redirection (computing)|I/O redirection]] in ways that are not possible in the traditional Bourne shell. For example, Bash can redirect [[standard streams#Standard output (stdout)|standard output]] (stdout) and [[standard streams#Standard error (stderr)|standard error]] (stderr) at the same time using the <tt>&></tt> operator. This is simpler to type than the Bourne shell equivalent '<tt>command > file 2>&1</tt>'.
+
В bash 3.0 появилась поддержка регулярных выражений Perl.
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 document]]s just as the Bourne shell always has. However, since version 2.05b Bash can redirect [[standard streams#Standard input (stdin)|standard input]] (stdin) from a "here string" using the <tt><<<</tt> operator.
+
Bash 4.0 поддержка массивов аналогичных awk:
 
 
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:
 
  
 
<source lang="bash">
 
<source lang="bash">
Строка 46: Строка 43:
 
</source>
 
</source>
  
===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:
+
Выражения со скобками, которые также называются чередованием, были скопированы из C shell и генерирует набор различных комбинаций. Строки не сортируются и обрабатываются в порядке слева направо:
  
 
<source lang="bash">
 
<source lang="bash">
Строка 54: Строка 51:
 
echo {a,b,c}{d,e,f} # ad ae af bd be bf cd ce cf
 
echo {a,b,c}{d,e,f} # ad ae af bd be bf cd ce cf
 
</source>
 
</source>
Brace expansions should not be used in portable shell scripts, because the Bourne shell will not produce the same output.
+
 
 +
Чередование не должно использоваться в портативных скриптах, т.к. Bourne shell его не поддерживает.
  
 
<source lang="bash">
 
<source lang="bash">
# A traditional shell does not produce the same output
 
 
echo a{p,c,d,b}e # a{p,c,d,b}e
 
echo a{p,c,d,b}e # a{p,c,d,b}e
 
</source>
 
</source>
  
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:
+
Когда чередование комбинируется со знаками подстановки, первым используется чередование, а затем символы заменяются в обычном режиме. Таким образом, список JPEG и PNG изображений в текущей директории может быть получен так:
  
 
<source lang="bash">
 
<source lang="bash">
ls *.{jpg,jpeg,png}   # expands to *.jpg *.jpeg *.png - after which,
+
ls *.{jpg,jpeg,png} # заменяется на *.jpg *.jpeg *.png - после чего обрабатываются шаблоны
                      # the wildcards are processed
 
 
</source>
 
</source>
  
===Startup scripts===
+
===Стартовые скрипты===
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 <tt>/etc/profile</tt>, if that file exists. After reading that file, it looks for <tt>~/.bash_profile</tt>, <tt>~/.bash_login</tt>, and <tt>~/.profile</tt>, 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 <tt>~/.bash_logout</tt>, if it exists.
 
 
 
When an interactive shell that is not a login shell is started, Bash reads and executes commands from <tt>~/.bashrc</tt>, if that file exists. This may be inhibited by using the <tt>--norc</tt> option. The <tt>--rcfile file</tt> option will force Bash to read and execute commands from <tt>file</tt> instead of <tt>~/.bashrc</tt>.
 
 
 
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.{{Citation needed|date=June 2010}}
 
 
 
===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 (Unix)|''shebang'']] ''line''" of ''#![[/bin]]/bash'' [[interpreter directive]] instead of ''#!/bin/sh''.
 
 
 
===Keyboard shortcuts===
 
The following shortcuts work when using default ([[Emacs]]) key bindings. [[Vim (text editor)|Vi]]-bindings can be enabled by running <code>set -o vi</code>.
 
 
 
{{See also|Readline}}
 
 
 
* {{Keypress|TAB}} : [[Autocomplete]]s from the cursor position.
 
* {{Keypress|Ctrl|a}} : moves the cursor to the line start (equivalent to the key {{keypress|[[home key|Home]]}}).
 
* {{Keypress|Ctrl|e}} : ([[wikt:end|end]]) moves the cursor to the line end (equivalent to the key {{keypress|[[end key|End]]}}).
 
* {{Keypress|Ctrl|p}} : ([[wikt:previous|previous]]) recalls the prior command (equivalent to the key {{keypress|[[arrow keys|Up]]}}).
 
* {{Keypress|Ctrl|n}} : ([[wikt:next|next]]) recalls the next command (equivalent to the key {{keypress|[[arrow keys|Down]]}}).
 
* {{Keypress|Ctrl|r}} : ([[wikt:research|research]]) recalls the last command including the specified character(s). A second {{keypress|Ctrl|r}} recalls the next anterior command which corresponds to the research
 
* {{Keypress|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 {{Keypress|Ctrl|q}} to return.
 
* {{Keypress|Ctrl|o}} : executes the found command from research.
 
* {{Keypress|Ctrl|l}} : clears the screen content (equivalent to the command <code>[[clear (Unix)|clear]]</code>).
 
* {{Keypress|Ctrl|u}} : clears the line content before the cursor and copies it into the [[clipboard (software)|clipboard]].
 
* {{Keypress|Ctrl|k}} : clears the line content after the cursor and copies it into the [[clipboard (software)|clipboard]].
 
* {{Keypress|Ctrl|w}} : clears the word before the cursor and copies it into the [[clipboard (software)|clipboard]].
 
* {{Keypress|Ctrl|y}} : ([[wikt:yank|yank]]) adds the [[clipboard (software)|clipboard]] content from the cursor position.
 
* {{Keypress|Ctrl|d}} : sends an EOF marker, which (unless disabled by an option) closes the current [[shell (computing)|shell]] (equivalent to the command <code>[[exit (command)|exit]]</code>). (Only if there is no text on the current line)
 
* {{Keypress|Ctrl|c}} : sends the signal [[SIGINT (POSIX)|SIGINT]] to the current task, which aborts and closes it.
 
* {{Keypress|Ctrl|z}} : sends the signal [[SIGTSTP]] to the current task, which suspends it. To execute it in background one can enter <code>bg</code>. To bring it back from background or suspension <code>fg ['process name or job id']</code> ([[wikt:foreground|foreground]]) can be issued.
 
* {{Keypress|Ctrl|x}} {{Keypress|Ctrl|x}} : (because x has a crossing shape) alternates the cursor with its old position.
 
* {{Keypress|Ctrl|x}} {{Keypress|Ctrl|e}} : edits the current line in the $EDITOR program, or [[vi]] if undefined.
 
* {{Keypress|Alt|f}} : ([[wikt:forward|forward]]) moves forward the cursor of one word.
 
* {{Keypress|Alt|b}} : ([[wikt:backward|backward]]) moves backward the cursor of one word.
 
* {{Keypress|Alt|Del}} : cuts the word before the cursor.
 
* {{Keypress|Alt|d}} : cuts the word after the cursor.
 
* {{Keypress|Alt|u}} : capitalizes every character from the cursor's position to the end of the current word.
 
* {{Keypress|Alt|l}} : lowers the case of every character from the cursor's position to the end of the current word.
 
* {{Keypress|Alt|c}} : capitalizes the character under the cursor and moves to the end of the word.
 
* {{Keypress|Alt|r}} : cancels the changes and put back the line as it was in the history.
 
 
 
 
 
  
==Введение==
+
Bash при запуске вызывает множество команд и различных скриптов.
'''Bash''' (Bourne-Again SHell) Самый распространенный командный интерпретатор, используемый по умолчанию в подавляющем количестве дистрибутивов GNU/Linux.
+
Когда Bash вызывается как интерактивная оболочка, первым делом он читает и вызывает команды из файла {{Path|/etc/profile}}. После чтения этого выполняются следующие файлы: {{Path|~/.bash_profile}}, {{Path|~/.bash_login}}, и {{Path|~/.profile}}. При выходе Bash выполняет команды из файла {{Path|~/.bash_logout}}.
 +
Также Bash использует файл {{Path|~/.bashrc}}. Это может быть отменено опцией ''--norc''. Опция ''--rcfile'' заставит Bash использовать команды из {{Path|~/.bashrc}}.
  
==Управляющие комбинации клавиш консоли==
+
==Комбинации клавиш==
 
{{Key|'''ctrl+u'''}}  удалить все символы от курсора до начала строки
 
{{Key|'''ctrl+u'''}}  удалить все символы от курсора до начала строки
  

Текущая версия на 02:53, 16 марта 2012

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

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

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

Особенности

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

Bash имеет много возможностей, которых не хватает в Bourne shell. Например, bash может выполнять вычисления с целыми числами без порождения внешних процессов. Bash упрощает перенаправление ввода/вывода способами, которые невозможны в традиционных шелах Борна. Например, Bash может перенаправить стандартный вывод (STDOUT) и стандартная ошибка (STDERR) используя оператор &>. Это проще напечатать, чем эквивалентная команда в Bourne Shell.

command > file 2>&1

При использовании функций (function) bash не совместим с Bourne/Korn/POSIX шелами, но понимает их синтаксис. В силу этих и других различий, bash скрипты редко работоспособной под sh и ksh, если намеренно написаны с совместимостью. Но в режиме POSIX, соответствие POSIX является почти идеальным.

С версии 2.05b bash может перенаправлять стандартный ввод (stdin) используя оператор <.

В bash 3.0 появилась поддержка регулярных выражений Perl.

Bash 4.0 поддержка массивов аналогичных 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"

Выражения со скобками

Выражения со скобками, которые также называются чередованием, были скопированы из C shell и генерирует набор различных комбинаций. Строки не сортируются и обрабатываются в порядке слева направо:

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

Чередование не должно использоваться в портативных скриптах, т.к. Bourne shell его не поддерживает.

echo a{p,c,d,b}e # a{p,c,d,b}e

Когда чередование комбинируется со знаками подстановки, первым используется чередование, а затем символы заменяются в обычном режиме. Таким образом, список JPEG и PNG изображений в текущей директории может быть получен так:

ls *.{jpg,jpeg,png} # заменяется на *.jpg *.jpeg *.png - после чего обрабатываются шаблоны

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

Bash при запуске вызывает множество команд и различных скриптов. Когда Bash вызывается как интерактивная оболочка, первым делом он читает и вызывает команды из файла /etc/profile. После чтения этого выполняются следующие файлы: ~/.bash_profile, ~/.bash_login, и ~/.profile. При выходе Bash выполняет команды из файла ~/.bash_logout. Также Bash использует файл ~/.bashrc. Это может быть отменено опцией --norc. Опция --rcfile заставит Bash использовать команды из ~/.bashrc.

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

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