3.1 Shell Syntax
When the shell reads input, it proceeds through a sequence of operations. If the input indicates the beginning of a comment, the shell ignores the comment symbol (‘#’), and the rest of that line.
当 shell 读到输入时,它会执行一系列操作。 如果输入以注释开头,则 shell 将忽略注释符号#以及该行的其余部分。
Otherwise, roughly speaking, the shell reads its input and divides the input into words and operators, employing the quoting rules to select which meanings to assign various words and characters.
否则,shell 读取其输入并将输入划分为单词和运算符,使用“引用”规则来决定各单词和字符的含义。
The shell then parses these tokens into commands and other constructs, removes the special meaning of certain words or characters, expands others, redirects input and output as needed, executes the specified command, waits for the command’s exit status, and makes that exit status available for further inspection or processing.
然后,shell 将这些标记解析为命令和其他结构,删除某些单词或字符的特殊含义,扩展一些字符,根据需要重定向输入和输出,执行指定的命令,等待命令执行结束并获取退出状态以便进一步检查或处理。
3.1.1 Shell Operation
The following is a brief description of the shell’s operation when it reads and executes a command. Basically, the shell does the following:
下面简单介绍一下shell在读取和执行命令时的操作。 基本上,shell 执行以下操作:
- Reads its input from a file (see Shell Scripts), from a string supplied as an argument to the
-cinvocation option (see Invoking Bash), or from the user’s terminal.
从各种渠道读取输入:文件(参见 3.8 Shell Scripts)、 bash -c 后面的字符串、用户终端。 - Breaks the input into words and operators, obeying the quoting rules described in Quoting. These tokens are separated by
metacharacters. Alias expansion is performed by this step (see Aliases).
将输入分解为单词和运算符,遵守3.1.2 Quoting中描述的引用规则。 这些标记由元字符分隔。 别名扩展也在这一步执行。 - Parses the tokens into simple and compound commands (see Shell Commands).
将符号解析为简单或复合命令(请参阅3.2 Shell Commands)。 - Performs the various shell expansions (see Shell Expansions), breaking the expanded tokens into lists of filenames (see Filename Expansion) and commands and arguments.
执行各种 shell 扩展(请参阅 3.5 Shell Expansions),将扩展的标记分解为文件名列表(请参阅文件名扩展)以及命令和参数。 - Performs any necessary redirections (see Redirections) and removes the redirection operators and their operands from the argument list.
执行任何必要的重定向(请参阅 3.6 Redirections)并从参数列表中删除重定向运算符及其操作数。 - Executes the command (see Executing Commands).
执行命令(请参阅3.7 Executing Commands 执行命令)。 - Optionally waits for the command to complete and collects its exit status (see Exit Status).
(可选)等待命令完成并收集其退出状态(请参阅3.7.5 Exit Status)。
3.1.2 Quoting
Quoting is used to remove the special meaning of certain characters or words to the shell. Quoting can be used to disable special treatment for special characters, to prevent reserved words from being recognized as such, and to prevent parameter expansion.
Each of the shell metacharacters (see Definitions) has special meaning to the shell and must be quoted if it is to represent itself. When the command history expansion facilities are being used (see History Interaction), the history expansion character, usually ‘!’, must be quoted to prevent history expansion. See Bash History Facilities, for more details concerning history expansion.
There are three quoting mechanisms: the escape character, single quotes, and double quotes.
3.1.2.1 Escape Character
A non-quoted backslash ‘\’ is the Bash escape character. It preserves the literal value of the next character that follows, with the exception of newline. If a \newline pair appears, and the backslash itself is not quoted, the \newline is treated as a line continuation (that is, it is removed from the input stream and effectively ignored).
没有被引号包围的\是Bash退出字符。它会保留下一个字符的字面含义(意思是echo \a等价于echo a),除非下一个字符是换行符。如果出现了\换行符,并且\没有被引号包围则\被视为行连续符号,就是换行符会从输入流中移除。
3.1.2.2 Single Quotes
Enclosing characters in single quotes (‘'’) preserves the literal value of each character within the quotes. A single quote may not occur between single quotes, even when preceded by a backslash.
以单引号包围的字符串会保留每个字符的字面含义。单引号不能被单引号包围,并且’也不能被单引号包围。
3.1.2.3 Double Quotes
Enclosing characters in double quotes (‘“’) preserves the literal value of all characters within the quotes, with the exception of ‘$’, ‘`’, ‘\’, and, when history expansion is enabled, ‘!’. When the shell is in POSIX mode (see Bash POSIX Mode), the ‘!’ has no special meaning within double quotes, even when history expansion is enabled. The characters ‘$’ and ‘`’ retain their special meaning within double quotes (see Shell Expansions). The backslash retains its special meaning only when followed by one of the following characters: ‘$’, ‘`’, ‘”’, ‘\’, or newline. Within double quotes, backslashes that are followed by one of these characters are removed. Backslashes preceding characters without a special meaning are left unmodified. A double quote may be quoted within double quotes by preceding it with a backslash. If enabled, history expansion will be performed unless an ‘!’ appearing in double quotes is escaped using a backslash. The backslash preceding the ‘!’ is not removed.
被双引号包围的字符会保留引号内字符的字面值,但$ ` 和\及启用历史命令扩展时的!除外。当终端处于POSIX模式时(参见Bash POSIX 模式),双引号内的!没有特殊含义,即使启用了历史扩展。在使用双引号时$和`保留其特殊含义(参见3.5 Shell Expansions)。反斜杠只有在后面跟着特定字符($ ` " \ 及 换行符)时保留特殊含义,反斜杠会被删除。没有特殊含义的字符前的反斜杠不会被删除。双引号可以通过在前面放置反斜杠再被双引号包围。在!前面放置反斜杠可以阻止历史命令扩展。在非历史命令扩展的场景下,叹号前面的反斜杠不会被删除(比如echo "\!"的输出是`!`)。
The special parameters ‘*’ and ‘@’ have special meaning when in double quotes (see Shell Parameter Expansion).
特殊参数*和@有特殊含义,参见3.5.3 Shell Parameter Expansion 参数扩展。
3.1.2.4 ANSI-C Quoting (C语言字符串)
Words of the form $'string' are treated specially. The word expands to string, with backslash-escaped characters replaced as specified by the ANSI C standard. Backslash escape sequences, if present, are decoded as follows:
$'字符串'形式的单词会被特殊处理,单词会被扩展为字符串,其中反斜杠转义的字符会按照C语言标准进行处理。如果转义序列存在,则按以下方式处理:
\aalert (bell)\bbackspace\e\Ean escape character (not ANSI C)\fform feed\nnewline\rcarriage return\thorizontal tab\vvertical tab\\backslash\'single quote\"double quote\?question mark\nnnthe eight-bit character whose value is the octal value nnn (one to three octal digits) (1到3位8进制数)\xHHthe eight-bit character whose value is the hexadecimal value HH (one or two hex digits) (1到2位16进制数)\uHHHHthe Unicode (ISO/IEC 10646) character whose value is the hexadecimal value HHHH (one to four hex digits) (1到4位16进制数)\UHHHHHHHHthe Unicode (ISO/IEC 10646) character whose value is the hexadecimal value HHHHHHHH (one to eight hex digits) (1到8位16进制数)\cxa control-x character (比如\cc代表Ctrl+C)
The expanded result is single-quoted, as if the dollar sign had not been present.
3.1.2.5 Locale-Specific Translation (本地翻译)
A double-quoted string preceded by a dollar sign (‘$’) will cause the string to be translated according to the current locale. The gettext infrastructure performs the message catalog lookup and translation, using the LC_MESSAGES and TEXTDOMAIN shell variables, as explained below. See the gettext documentation for additional details. If the current locale is C or POSIX, or if there are no translations available, the dollar sign is ignored. If the string is translated and replaced, the replacement is double-quoted.
在双引号前面的字符串前面加上美元符号会导致字符串根据区域翻译。gettext方法会使用LC_MESSAGES和TEXTDOMAIN两个shell变量执行消息目录查找和翻译。有关详细信息参见gettext文档。如果当前语言环境是C或POSIX,或没有可用的翻译,会忽略美元符号。如果字符串被替换,则替换后使用双引号模式。
Some systems use the message catalog selected by the LC_MESSAGES shell variable. Others create the name of the message catalog from the value of the TEXTDOMAIN shell variable, possibly adding a suffix of ‘.mo’. If you use the TEXTDOMAIN variable, you may need to set the TEXTDOMAINDIR variable to the location of the message catalog files. Still others use both variables in this fashion: TEXTDOMAINDIR/LC_MESSAGES/LC_MESSAGES/TEXTDOMAIN.mo.
3.1.3 Comments
In a non-interactive shell, or an interactive shell in which the interactive_comments option to the shopt builtin is enabled (see The Shopt Builtin), a word beginning with ‘#’ causes that word and all remaining characters on that line to be ignored. An interactive shell without the interactive_comments option enabled does not allow comments. The interactive_comments option is on by default in interactive shells. See Interactive Shells, for a description of what makes a shell interactive.
在非交互终端中,或者交互终端且交互注释选项被设置为允许(可以通过shopt命令设置),则以#开头的单词及后续会被忽略。如果禁用了交互注释选项,则不允许注释,默认情况下允许注释。(参见交互终端,了解什么情况下终端可交互)
3.2 Shell Commands
A simple shell command such as echo a b c consists of the command itself followed by arguments, separated by spaces.
简单的命令,例如echo a b c包含了命令本身及命令参数,以空格分隔。
More complex shell commands are composed of simple commands arranged together in a variety of ways: in a pipeline in which the output of one command becomes the input of a second, in a loop or conditional construct, or in some other grouping.
更复杂的shell命令由多种方式排列在一起的简单命令组成:在管道中,第一个命令的输出成为第二个命令的输入;在循环或条件结构中,或在其它分组中。
3.2.1 Reserved Words
Reserved words are words that have special meaning to the shell. They are used to begin and end the shell’s compound commands.
保留字是对终端有特殊含义的单词,用于开始和结果shell的复合命令。
if |
then |
elif |
else |
fi |
time |
|---|---|---|---|---|---|
for |
in |
until |
while |
do |
done |
case |
esac |
coproc |
select |
function |
|
{
|
} |
[[ |
]] |
! |
in is recognized as a reserved word if it is the third word of a case or select command. in and do are recognized as reserved words if they are the third word in a for command.
in在成为case或select命令的第3个单词的情况下被当做保留字,in或do在成为for命令的第3个单词的情况下被当作保留字。
3.2.2 Simple Commands
A simple command is the kind of command encountered most often. It’s just a sequence of words separated by blanks, terminated by one of the shell’s control operators (see Definitions). The first word generally specifies a command to be executed, with the rest of the words being that command’s arguments.
简单命令是最常见和一种命令,就是以空格分隔的单词序列,以终端的控制操作终止。控制操作是以下字符:换行符或|| && & ; ;; ;& ;;& | |& ( )。第一个单词通常是一个命令,其余部分是命令的参数。
The return status (see Exit Status) of a simple command is its exit status as provided by the POSIX 1003.1 waitpid function, or 128+n if the command was terminated by signal n.
简单命令的返回状态(参见3.7.5 Exit Status)是由POSIX 1003.1 waitpid 函数提供的退出状态,如果由信号n终止则返回128+n。
3.2.3 Pipelines
A pipeline is a sequence of one or more commands separated by one of the control operators ‘|’ or ‘|&’.
管道是控制字符|或|&分隔的一系列命令。
The format for a pipeline is
[time [-p]] [!] command1 [ | or |& command2 ] …
讯享网
The output of each command in the pipeline is connected via a pipe to the input of the next command. That is, each command reads the previous command’s output. This connection is performed before any redirections specified by the command.
管道中每个命令的输出通过|连接到下一个命令的输入,因此每个命令读取之前命令的输出。这种连接会在所有重定向(3.6 Redirections)之前执行。
If ‘|&’ is used, command1’s standard error, in addition to its standard output, is connected to command2’s standard input through the pipe; it is shorthand for 2>&1 |. This implicit redirection of the standard error to the standard output is performed after any redirections specified by the command.
如果使用|&,则命令1的错误输出和标准输出都会发送到命令2的输入中,这是2>&1 |的缩写。错误到标准输出的这种隐式重定向是在命令指定的任何重定向之后执行的。
The reserved word time causes timing statistics to be printed for the pipeline once it finishes. The statistics currently consist of elapsed (wall-clock) time and user and system time consumed by the command’s execution. The -p option changes the output format to that specified by POSIX. When the shell is in POSIX mode (see Bash POSIX Mode), it does not recognize time as a reserved word if the next token begins with a ‘-’. The TIMEFORMAT variable may be set to a format string that specifies how the timing information should be displayed. See Bash Variables, for a description of the available formats. The use of time as a reserved word permits the timing of shell builtins, shell functions, and pipelines. An external time command cannot time these easily.
保留字time会在管道执行结束后打印时间统计信息。目前,统计信息包括命令执行消耗的已用时间、用户时间和系统时间。-p选项把输出格式改变成由POSIX指定,当终端处于POSIX模式,如果下一个标记以-开头,则无法将time识别为保留字,可以通过设置TIMEFORMAT变量指定时间信息如何打印。查看Bash变量,了解可用格式。将time作为保留字允许对shell内置命令、函数和管道进行计时,外部事件命令很难对这些操作计时。
When the shell is in POSIX mode (see Bash POSIX Mode), time may be followed by a newline. In this case, the shell displays the total user and system time consumed by the shell and its children. The TIMEFORMAT variable may be used to specify the format of the time information.
当shell处于POSIX模式时,time后面可能跟着换行符,这种情况下shell会显示shell及其子进程消耗的总用户和系统时间。可以通过TIMEFORMAT指定时间信息的格式。
If the pipeline is not executed asynchronously (see Lists), the shell waits for all commands in the pipeline to complete.
如果管道不是异步执行的(参见3.2.4 Lists of Commands),shell会等待管道中的所有命令执行结束。
Each command in a pipeline is executed in its own subshell, which is a separate process (see Command Execution Environment). If the lastpipe option is enabled using the shopt builtin (see The Shopt Builtin), the last element of a pipeline may be run by the shell process.
管道中的所有命令都在其子shell中执行,这是一个单独的进程(参见3.7.3 Command Execution Environment 命令执行环境)。如果通过内置的shopt命令将lastpipe选项打开,则管道的最后一个命令会由shell进程执行。
The exit status of a pipeline is the exit status of the last command in the pipeline, unless the pipefail option is enabled (see The Set Builtin). If pipefail is enabled, the pipeline’s return status is the value of the last (rightmost) command to exit with a non-zero status, or zero if all commands exit successfully. If the reserved word ‘!’ precedes the pipeline, the exit status is the logical negation of the exit status as described above. The shell waits for all commands in the pipeline to terminate before returning a value.
管道的退出状态是管道中最后一个命令的退出状态。如果启用了pipefail选项(参见set命令),则管道的退出状态是最后一个非0的退出状态,或者如果所有命令都正常退出则返回0。如果保留字!在管道之前,则退出状态是上述结果取反。shell在返回之前等待管道中的所有命令终止。
3.2.4 Lists of Commands
A list is a sequence of one or more pipelines separated by one of the operators ‘;’, ‘&’, ‘&&’, or ‘||’, and optionally terminated by one of ‘;’, ‘&’, or a newline.
列表是一个管道,以运算符; & && ||分割,以; &或换行符结尾。
Of these list operators, ‘&&’ and ‘||’ have equal precedence, followed by ‘;’ and ‘&’, which have equal precedence.
在这些列表运算符中,&&和||具有相同的优先级,;和&具有相同的优先级,后两个比前两个优先级低。
A sequence of one or more newlines may appear in a list to delimit commands, equivalent to a semicolon.
一个或多个换行符可以出现在列表中分隔命令,等价于分号。
If a command is terminated by the control operator ‘&’, the shell executes the command asynchronously in a subshell. This is known as executing the command in the background, and these are referred to as asynchronous commands. The shell does not wait for the command to finish, and the return status is 0 (true). When job control is not active (see Job Control), the standard input for asynchronous commands, in the absence of any explicit redirections, is redirected from /dev/null.
如果命令以&终止,则终端会在子shell中异步执行命令,称为后台执行命令。shell不等待命令完成,退出状态是0(真)。当作业控制未激活时,异步命令的标准输入在未显式重定向的情况下被重定向到/dev/null。
Commands separated by a ‘;’ are executed sequentially; the shell waits for each command to terminate in turn. The return status is the exit status of the last command executed.
用分号分隔的命令顺序执行,shell等待每个命令依次终止。退出状态是最后一个命令的退出状态。
AND and OR lists are sequences of one or more pipelines separated by the control operators ‘&&’ and ‘||’, respectively. AND and OR lists are executed with left associativity.
与和或列表是一个或多个管道的序列,分别通过&&和||分隔。两个都以左结合方式执行。
An AND list has the form
讯享网command1 && command2
command2 is executed if, and only if, command1 returns an exit status of zero (success).
与列表的形式是命令1&&命令2,命令2只有在命令1的返回值是0(成功)的情况下才会执行。
An OR list has the form
command1 || command2
command2 is executed if, and only if, command1 returns a non-zero exit status.
或列表的形式是命令1||命令2,命令2仅在命令1的返回值非0(失败)的情况下执行。
The return status of AND and OR lists is the exit status of the last command executed in the list.
与或列表的退出状态是最后一个命令的返回值。
3.2.5 Compound Commands 复合命令
Compound commands are the shell programming language constructs. Each construct begins with a reserved word or control operator and is terminated by a corresponding reserved word or operator. Any redirections (see Redirections) associated with a compound command apply to all commands within that compound command unless explicitly overridden.
复合命令是shell编程语言结构,每个结构都以保留字或控制运算符开始,并且以对应的保留字或运算符终止。与复合命令的相关的任何重定向都适用于复合命令中的所有命令,除非明确覆盖。
In most cases a list of commands in a compound command’s description may be separated from the rest of the command by one or more newlines, and may be followed by a newline in place of a semicolon.
在大多数情况下,复合命令描述中的命令列表可以通过换行符与其它部分分开,并且可以用换行符代替分号。(语法结构中的分号不能被替换)
Bash provides looping constructs, conditional commands, and mechanisms to group commands and execute them as a unit.
Bash提供了循环结构、条件命令及将命令分组执行的机制。
3.2.5.1 Looping Constructs 循环结构
Bash supports the following looping constructs.
Note that wherever a ‘;’ appears in the description of a command’s syntax, it may be replaced with one or more newlines.
注意无论分号出现在命令语法的什么部分,都可以用换行符替换。
untilThe syntax of the
untilcommand is:until test-commands; do consequent-commands; doneuntil命令的语法是:
until 测试命令; do 后续命令列表; doneExecute consequent-commands as long as test-commands has an exit status which is not zero. The return status is the exit status of the last command executed in consequent-commands, or zero if none was executed.
只要
测试命令的返回值非0,就不断执行后续命令列表。整个结构的返回值是后续命令列表的最后一个命令的返回值,没有命令时返回0。测试命令参见:
- https://www.gnu.org/software/bash/manual/html_node/Bourne-Shell-Builtins.html#Bourne-Shell-Builtins 中的
test和[命令 - https://www.gnu.org/software/bash/manual/html_node/Bash-Conditional-Expressions.html
- https://www.gnu.org/software/bash/manual/html_node/Bourne-Shell-Builtins.html#Bourne-Shell-Builtins 中的
whileThe syntax of the
whilecommand is:while test-commands; do consequent-commands; donewhile命令的语法是:
while 测试命令列表; do 后续命令列表; doneExecute consequent-commands as long as test-commands has an exit status of zero. The return status is the exit status of the last command executed in consequent-commands, or zero if none was executed.
只要
测试命令列表的返回值为0,就不断执行后续命令列表。整个结构的返回值是后续命令列表的最后一个命令的返回值,没有命令时返回0。forThe syntax of the
forcommand is:for name [ [in [words …] ] ; ] do commands; donefor命令的语法是:
for 变量名 [ [in [单词列表] ] ; ] do 命令列表; doneExpand words (see Shell Expansions), and execute commands once for each member in the resultant list, with name bound to the current member. If ‘in words’ is not present, the
forcommand executes the commands once for each positional parameter that is set, as ifin "$@"had been specified (see Special Parameters).展开
单词列表(参见Shell扩展),对于列表中的每一个成员执行一次命令,并将成员绑定到变量名。如果in 单词列表不存在,for命令对设置的每个位置参数执行一次命令,相当于for 变量名 in $@(参见特殊参数)。注意变量名不带$,后续访问时要使用$变量名。The return status is the exit status of the last command that executes. If there are no items in the expansion of words, no commands are executed, and the return status is zero.
整个结构的返回值是最后一个命令的返回值。如果
单词列表中没有元素或没有命令执行则返回0.An alternate form of the
forcommand is also supported:for (( expr1 ; expr2 ; expr3 )) ; do commands ; donefor命令也支持另一种形式:
for (( 表达式1 ; 表达式2 ; 表达式3 )) ; do 命令列表 ; doneFirst, the arithmetic expression expr1 is evaluated according to the rules described below (see Shell Arithmetic). The arithmetic expression expr2 is then evaluated repeatedly until it evaluates to zero. Each time expr2 evaluates to a non-zero value, commands are executed and the arithmetic expression expr3 is evaluated. If any expression is omitted, it behaves as if it evaluates to 1. The return value is the exit status of the last command in commands that is executed, or false if any of the expressions is invalid.
首先,根据以下规则(参见Shell算术)计算算术
表达式1。然后重复计算算术表达式2直到计算结果为0。每次表达式2计算出非0值,命令都会被执行,并且计算表达式3。如果省略了任何表达式,当将表达式结果视为1。整个结构的返回值是命令中的最后一个命令列表的返回值,或者如果任何表达式无效返回false。The
breakandcontinuebuiltins (see Bourne Shell Builtins) may be used to control loop execution.
3.2.5.2 Conditional Constructs
- if
The syntax of the
ifcommand is:讯享网
if test-commands; then consequent-commands; [elif more-test-commands; then more-consequents;] [else alternate-consequents;] fiif 测试命令列表; then 后续命令列表1; [elif 更多测试命令; then 后续命令列表2; ] [else 替代命令列表; ] fiThe test-commands list is executed, and if its return status is zero, the consequent-commands list is executed. If test-commands returns a non-zero status, each
eliflist is executed in turn, and if its exit status is zero, the corresponding more-consequents is executed and the command completes. If ‘else alternate-consequents’ is present, and the final command in the finaliforelifclause has a non-zero exit status, then alternate-consequents is executed. The return status is the exit status of the last command executed, or zero if no condition tested true.执行
测试命令列表,如果其返回值为0,则后续命令列表1开始执行。如果测试命令列表返回非0,每个elif语句依次执行,如果其退出状态为0,对应的测试命令列表会被执行,如果else 替代命令列表存在,并且if或elif测试命令中的最后一个命令返回值非0,则替代命令列表会执行。整个结构返回状态是最后一个命令的状态,或返回0如果没有条件成立。 - case
The syntax of the
casecommand is:case word in [ [(] pattern [| pattern]…) command-list ;;]… esaccase 单词 in [ [(] 模式 [| 模式]…) 命令列表 ;;]…esaccasewill selectively execute the command-list corresponding to the first pattern that matches word. The match is performed according to the rules described below in Pattern Matching. If thenocasematchshell option (see the description ofshoptin The Shopt Builtin) is enabled, the match is performed without regard to the case of alphabetic characters. The ‘|’ is used to separate multiple patterns, and the ‘)’ operator terminates a pattern list. A list of patterns and an associated command-list is known as a clause.case 会根据第一个匹配word的模式选择性的执行命令列表。匹配规则是模式匹配。
|用于分割多个模式,)用于结束模式列表。Each clause must be terminated with ‘;;’, ‘;&’, or ‘;;&’. The word undergoes tilde expansion, parameter expansion, command substitution, arithmetic expansion, and quote removal (see Shell Parameter Expansion) before matching is attempted. Each pattern undergoes tilde expansion, parameter expansion, command substitution, and arithmetic expansion.
每个语句都必须以
;;;&或;;&结束。在尝试匹配之前,单词会经历多次扩展,模式也会经历参数扩展,但不包含引号删除步骤。There may be an arbitrary number of
caseclauses, each terminated by a ‘;;’, ‘;&’, or ‘;;&’. The first pattern that matches determines the command-list that is executed. It’s a common idiom to use ‘*’ as the final pattern to define the default case, since that pattern will always match.可以用
*作为最后一个条件,类似于if语句中的else,因为一定会被匹配。Here is an example using
casein a script that could be used to describe one interesting feature of an animal:讯享网
echo -n "Enter the name of an animal: " read ANIMAL echo -n "The $ANIMAL has " case $ANIMAL in horse | dog | cat) echo -n "four";; man | kangaroo ) echo -n "two";; *) echo -n "an unknown number of";; esac echo " legs."If the ‘;;’ operator is used, no subsequent matches are attempted after the first pattern match. Using ‘;&’ in place of ‘;;’ causes execution to continue with the command-list associated with the next clause, if any. Using ‘;;&’ in place of ‘;;’ causes the shell to test the patterns in the next clause, if any, and execute any associated command-list on a successful match, continuing the case statement execution as if the pattern list had not matched.
;;表示在第一次匹配成功后不会进行后续尝试。;&表示执行下一个模式的命令列表(不论是否匹配)。;;&表示测试下一个模式,如果成功则执行其命令列表。The return status is zero if no pattern is matched. Otherwise, the return status is the exit status of the command-list executed.
- select
The
selectconstruct allows the easy generation of menus. It has almost the same syntax as theforcommand:选择构造可以轻松产生菜单。 它的语法几乎与for命令一致:
select name [in words …]; do commands; doneThe list of words following
inis expanded, generating a list of items. The set of expanded words is printed on the standard error output stream, each preceded by a number. If the ‘in words’ is omitted, the positional parameters are printed, as if ‘in “$@”’ had been specified. ThePS3prompt is then displayed and a line is read from the standard input. If the line consists of a number corresponding to one of the displayed words, then the value of name is set to that word. If the line is empty, the words and prompt are displayed again. IfEOFis read, theselectcommand completes. Any other value read causes name to be set to null. The line read is saved in the variableREPLY.执行之后会弹出一个菜单,通过输入序号可以选择一项,选择的序号放到$REPLY变量中,选择的值放到变量名中。
The commands are executed after each selection until a
breakcommand is executed, at which point theselectcommand completes.Here is an example that allows the user to pick a filename from the current directory, and displays the name and index of the file selected.
讯享网
select fname in *; do echo you picked $fname \($REPLY\) break; done ((…))(( 算术表达式 ))The arithmetic expression is evaluated according to the rules described below (see Shell Arithmetic). If the value of the expression is non-zero, the return status is 0; otherwise the return status is 1. This is exactly equivalent to
let "expression"如果算术表达式的结果非0则返回0,否则返回1,就是对表达式取反。等价于 let “表达式”。
See Bash Builtins, for a full description of theletbuiltin.[[…]][[ 条件表达式 ]]Return a status of 0 or 1 depending on the evaluation of the conditional expression expression. Expressions are composed of the primaries described below in Bash Conditional Expressions. Word splitting and filename expansion are not performed on the words between the
[[and]]; tilde expansion, parameter and variable expansion, arithmetic expansion, command substitution, process substitution, and quote removal are performed. Conditional operators such as ‘-f’ must be unquoted to be recognized as primaries.根据条件表达式的结果返回0或1(0代表真)。有些扩展不执行(单词分割和文件名扩展)。条件运算符例如
-f不能有引号。When used with
[[, the ‘<’ and ‘>’ operators sort lexicographically using the current locale.大小于号按照词典方式排序。
When the ‘’ and ‘!=’ operators are used, the string to the right of the operator is considered a pattern and matched according to the rules described below in Pattern Matching, as if the
extglobshell option were enabled. The ‘=’ operator is identical to ‘’. If thenocasematchshell option (see the description ofshoptin The Shopt Builtin) is enabled, the match is performed without regard to the case of alphabetic characters. The return value is 0 if the string matches (‘==’) or does not match (‘!=’) the pattern, and 1 otherwise. Any part of the pattern may be quoted to force the quoted portion to be matched as a string.==和!=为模式匹配操作,运算符右边的是模式。返回0代表匹配。An additional binary operator, ‘=~’, is available, with the same precedence as ‘==’ and ‘!=’. When it is used, the string to the right of the operator is considered a POSIX extended regular expression and matched accordingly (using the POSIX
regcompandregexecinterfaces usually described in regex(3)). The return value is 0 if the string matches the pattern, and 1 otherwise. If the regular expression is syntactically incorrect, the conditional expression’s return value is 2. If thenocasematchshell option (see the description ofshoptin The Shopt Builtin) is enabled, the match is performed without regard to the case of alphabetic characters. Any part of the pattern may be quoted to force the quoted portion to be matched as a string. Bracket expressions in regular expressions must be treated carefully, since normal quoting characters lose their meanings between brackets. If the pattern is stored in a shell variable, quoting the variable expansion forces the entire pattern to be matched as a string.=~为正则匹配,运算符右侧是正则表达式。The pattern will match if it matches any part of the string. Anchor the pattern using the ‘^’ and ‘$’ regular expression operators to force it to match the entire string. The array variable
BASH_REMATCHrecords which parts of the string matched the pattern. The element ofBASH_REMATCHwith index 0 contains the portion of the string matching the entire regular expression. Substrings matched by parenthesized subexpressions within the regular expression are saved in the remainingBASH_REMATCHindices. The element ofBASH_REMATCHwith index n is the portion of the string matching the nth parenthesized subexpression.正则表达式与字符串中的任何一部分匹配都视为匹配,可以使用
^和$强制匹配整个字符串。BASH_REMATCH存放了匹配结果列表。For example, the following will match a line (stored in the shell variable line) if there is a sequence of characters anywhere in the value consisting of any number, including zero, of characters in the
spacecharacter class, zero or one instances of ‘a’, then a ‘b’:讯享网
[[ $line =~ [[:space:]]*(a)?b ]]That means values like ‘aab’ and ‘ aaaaaab’ will match, as will a line containing a ‘b’ anywhere in its value.
Storing the regular expression in a shell variable is often a useful way to avoid problems with quoting characters that are special to the shell. It is sometimes difficult to specify a regular expression literally without using quotes, or to keep track of the quoting used by regular expressions while paying attention to the shell’s quote removal. Using a shell variable to store the pattern decreases these problems. For example, the following is equivalent to the above:
将正则表达式存储在变量中避免引号的问题。
pattern='[[:space:]]*(a)?b' [[ $line =~ $pattern ]]If you want to match a character that’s special to the regular expression grammar, it has to be quoted to remove its special meaning. This means that in the pattern ‘xxx.txt’, the ‘.’ matches any character in the string (its usual regular expression meaning), but in the pattern ‘“xxx.txt”’ it can only match a literal ‘.’. Shell programmers should take special care with backslashes, since backslashes are used both by the shell and regular expressions to remove the special meaning from the following character. The following two sets of commands are not equivalent:
如果想匹配正则表达式中的特殊字符(而不想执行正则表达式匹配),则应该用引号包围。正则表达式中的
.表示匹配任意字符。讯享网
pattern='\.' [[ . =~ $pattern ]] [[ . =~ \. ]] [[ . =~ "$pattern" ]] [[ . =~ '\.' ]]The first two matches will succeed, but the second two will not, because in the second two the backslash will be part of the pattern to be matched. In the first two examples, the backslash removes the special meaning from ‘.’, so the literal ‘.’ matches. If the string in the first examples were anything other than ‘.’, say ‘a’, the pattern would not match, because the quoted ‘.’ in the pattern loses its special meaning of matching any single character.
如果想匹配正则表达式中的特殊字符(比如
.),需要用引号包围。对于反斜杠要很小心,因为在正则表达式和shell中它都是特殊字符。pattern是\.,前两个是在尝试匹配正则表达式\.,表示匹配小数点,后两个在匹配普通字符串\.,而不是正则表达式。Expressions may be combined using the following operators, listed in decreasing order of precedence:
表达式可以使用以下运算符组合,按优先级降序排列:
( expression )Returns the value of expression. This may be used to override the normal precedence of operators.
! expressionTrue if expression is false.
expression1 && expression2True if both expression1 and expression2 are true.
expression1 || expression2True if either expression1 or expression2 is true.
The
&&and||operators do not evaluate expression2 if the value of expression1 is sufficient to determine the return value of the entire conditional expression.
3.2.5.3 Grouping Commands 命令组
Bash provides two ways to group a list of commands to be executed as a unit. When commands are grouped, redirections may be applied to the entire command list. For example, the output of all the commands in the list may be redirected to a single stream.
()( list )Placing a list of commands between parentheses causes a subshell environment to be created (see Command Execution Environment), and each of the commands in list to be executed in that subshell. Since the list is executed in a subshell, variable assignments do not remain in effect after the subshell completes.将命令放到括号中会创建子shell环境。
{}{ list; }Placing a list of commands between curly braces causes the list to be executed in the current shell context. No subshell is created. The semicolon (or newline) following list is required.在当前shell中执行一组命令。末尾的分号是必须的。(跟不加大括号有什么区别?)
In addition to the creation of a subshell, there is a subtle difference between these two constructs due to historical reasons. The braces are
reserved words, so they must be separated from the list byblanks or other shell metacharacters. The parentheses areoperators, and are recognized as separate tokens by the shell even if they are not separated from the list by whitespace.大括号是保留字,需要有空格分隔,圆括号是运算符,不需要空格。
The exit status of both of these constructs is the exit status of list.
3.2.6 Coprocesses 协同进程
A coprocess is a shell command preceded by the coproc reserved word. A coprocess is executed asynchronously in a subshell, as if the command had been terminated with the ‘&’ control operator, with a two-way pipe established between the executing shell and the coprocess.
协同进程是前面带有 coproc 保留字的 shell 命令。 协进程在子 shell 中异步执行,在执行 shell 和协进程之间建立了双向管道。
The format for a coprocess is:
coproc [NAME] command [redirections]
协同进程的语法是: coproc [名称] 命令 [重定向]
This creates a coprocess named NAME. If NAME is not supplied, the default name is COPROC. NAME must not be supplied if command is a simple command (see Simple Commands); otherwise, it is interpreted as the first word of the simple command.
简单命令不能提供名称,否则名称会被视为命令的一部分。(非简单命令指3.2.5.3的命令组)
When the coprocess is executed, the shell creates an array variable (see Arrays) named NAME in the context of the executing shell. The standard output of command is connected via a pipe to a file descriptor in the executing shell, and that file descriptor is assigned to NAME[0]. The standard input of command is connected via a pipe to a file descriptor in the executing shell, and that file descriptor is assigned to NAME[1]. This pipe is established before any redirections specified by the command (see Redirections). The file descriptors can be utilized as arguments to shell commands and redirections using standard word expansions. Other than those created to execute command and process substitutions, the file descriptors are not available in subshells.
在协同进程执行时,会在当前shell中创建一个文件描述符数组变量名称,命令的输出连接到名称[0],输入连接到名称[1]。管道建立在命令的重定向之前。文件描述符可以用于命令的参数或重定向,但不能用于子shell(因为不在当前shell进程中)。例如,可以通过 echo 123 >&名称[1] 向其输入数据。
The process ID of the shell spawned to execute the coprocess is available as the value of the variable NAME_PID. The wait builtin command may be used to wait for the coprocess to terminate.
进程ID可以通过变量NAME_PID得到。
Since the coprocess is created as an asynchronous command, the coproc command always returns success. The return status of a coprocess is the exit status of command.
3.2.7 GNU Parallel
There are ways to run commands in parallel that are not built into Bash. GNU Parallel is a tool to do just that.
有一些方法可以并行运行 Bash 中未内置的命令。 GNU Parallel 就是一个可以做到这一点的工具。
GNU Parallel, as its name suggests, can be used to build and run commands in parallel. You may run the same command with different arguments, whether they are filenames, usernames, hostnames, or lines read from files. GNU Parallel provides shorthand references to many of the most common operations (input lines, various portions of the input line, different ways to specify the input source, and so on). Parallel can replace xargs or feed commands from its input sources to several different instances of Bash.
For a complete description, refer to the GNU Parallel documentation. A few examples should provide a brief introduction to its use.
For example, it is easy to replace xargs to gzip all html files in the current directory and its subdirectories:
讯享网find . -type f -name '*.html' -print | parallel gzip
先找出所有HTML文件再并行压缩。
If you need to protect special characters such as newlines in file names, use find’s -print0 option and parallel’s -0 option.
You can use Parallel to move files from the current directory when the number of files is too large to process with one mv invocation:
将文件并行移动到一个文件夹:
printf '%s\n' * | parallel mv {} destdir
As you can see, the {} is replaced with each line read from standard input. While using ls will work in most instances, it is not sufficient to deal with all filenames. printf is a shell builtin, and therefore is not subject to the kernel’s limit on the number of arguments to a program, so you can use ‘*’ (but see below about the dotglob shell option). If you need to accommodate special characters in filenames, you can use
讯享网printf '%s\0' * | parallel -0 mv {} destdir
as alluded to above.
This will run as many mv commands as there are files in the current directory. You can emulate a parallel xargs by adding the -X option:
printf '%s\0' * | parallel -0 -X mv {} destdir
(You may have to modify the pattern if you have the dotglob option enabled.)
GNU Parallel can replace certain common idioms that operate on lines read from a file (in this case, filenames listed one per line):
讯享网 while IFS= read -r x; do do-something1 "$x" "config-$x" do-something2 < "$x" done < file | process-output
with a more compact syntax reminiscent of lambdas:
cat list | parallel "do-something1 {} config-{} ; do-something2 < {}" | process-output
Parallel provides a built-in mechanism to remove filename extensions, which lends itself to batch file transformations or renaming:
讯享网ls *.gz | parallel -j+0 "zcat {} | bzip2 >{.}.bz2 && rm {}"
This will recompress all files in the current directory with names ending in .gz using bzip2, running one job per CPU (-j+0) in parallel. (We use ls for brevity here; using find as above is more robust in the face of filenames containing unexpected characters.) Parallel can take arguments from the command line; the above can also be written as
parallel "zcat {} | bzip2 >{.}.bz2 && rm {}" ::: *.gz
If a command generates output, you may want to preserve the input order in the output. For instance, the following command
讯享网{ echo foss.org.my ; echo debian.org ; echo freenetproject.org ; } | parallel traceroute
will display as output the traceroute invocation that finishes first. Adding the -k option
{ echo foss.org.my ; echo debian.org ; echo freenetproject.org ; } | parallel -k traceroute
will ensure that the output of traceroute foss.org.my is displayed first.
Finally, Parallel can be used to run a sequence of shell commands in parallel, similar to ‘cat file | bash’. It is not uncommon to take a list of filenames, create a series of shell commands to operate on them, and feed that list of commands to a shell. Parallel can speed this up. Assuming that file contains a list of shell commands, one per line,
讯享网parallel -j 10 < file
will evaluate the commands using the shell (since no explicit command is supplied as an argument), in blocks of ten shell jobs at a time.
… (主要介绍parallel命令的用法)
3.3 Shell Functions
Shell functions are a way to group commands for later execution using a single name for the group. They are executed just like a “regular” command. When the name of a shell function is used as a simple command name, the list of commands associated with that function name is executed. Shell functions are executed in the current shell context; no new process is created to interpret them.
Functions are declared using this syntax:
fname () compound-command [ redirections ]
or
讯享网function fname [()] compound-command [ redirections ]
This defines a shell function named fname. The reserved word function is optional. If the function reserved word is supplied, the parentheses are optional. The body of the function is the compound command compound-command (see Compound Commands). That command is usually a list enclosed between { and }, but may be any compound command listed above, with one exception: If the function reserved word is used, but the parentheses are not supplied, the braces are required. compound-command is executed whenever fname is specified as the name of a command. When the shell is in POSIX mode (see Bash POSIX Mode), fname must be a valid shell name and may not be the same as one of the special builtins (see Special Builtins). In default mode, a function name can be any unquoted shell word that does not contain ‘$’. Any redirections (see Redirections) associated with the shell function are performed when the function is executed. A function definition may be deleted using the -f option to the unset builtin (see Bourne Shell Builtins).
保留字function是可选的,如果提供了function,圆括号就是可选的。函数体是3.2.5 Compound Commands 复合命令。如果没有圆括号,则必须有大括号。
The exit status of a function definition is zero unless a syntax error occurs or a readonly function with the same name already exists. When executed, the exit status of a function is the exit status of the last command executed in the body.
Note that for historical reasons, in the most common usage the curly braces that surround the body of the function must be separated from the body by blanks or newlines. This is because the braces are reserved words and are only recognized as such when they are separated from the command list by whitespace or another shell metacharacter. Also, when using the braces, the list must be terminated by a semicolon, a ‘&’, or a newline.
命令列表必须以; & 换行终止
When a function is executed, the arguments to the function become the positional parameters during its execution (see Positional Parameters). The special parameter ‘#’ that expands to the number of positional parameters is updated to reflect the change. Special parameter 0 is unchanged. The first element of the FUNCNAME variable is set to the name of the function while the function is executing.
当函数执行时,函数参数成为位置参数,特殊参数#表示位置参数的数量,特殊参数0不会改变,FUNCNAME变量的第一个参数被设置为函数名。
All other aspects of the shell execution environment are identical between a function and its caller with these exceptions: the DEBUG and RETURN traps are not inherited unless the function has been given the trace attribute using the declare builtin or the -o functrace option has been enabled with the set builtin, (in which case all functions inherit the DEBUG and RETURN traps), and the ERR trap is not inherited unless the -o errtrace shell option has been enabled. See Bourne Shell Builtins, for the description of the trap builtin.
关于信号trap的一些说明。
The FUNCNEST variable, if set to a numeric value greater than 0, defines a maximum function nesting level. Function invocations that exceed the limit cause the entire command to abort.
FUNCNSET可以用于限定函数嵌套层次。
If the builtin command return is executed in a function, the function completes and execution resumes with the next command after the function call. Any command associated with the RETURN trap is executed before execution resumes. When a function completes, the values of the positional parameters and the special parameter ‘#’ are restored to the values they had prior to the function’s execution. If a numeric argument is given to return, that is the function’s return status; otherwise the function’s return status is the exit status of the last command executed before the return.
内置命令return用于退出函数的执行。函数的返回值是return后的数字,或最后一个命令的退出状态。
Variables local to the function may be declared with the local builtin. These variables are visible only to the function and the commands it invokes. This is particularly important when a shell function calls other functions.
局部变量可以用内置命令local声名。
Local variables “shadow” variables with the same name declared at previous scopes. For instance, a local variable declared in a function hides a global variable of the same name: references and assignments refer to the local variable, leaving the global variable unmodified. When the function returns, the global variable is once again visible.
局部变量会隐藏以前的作用域的同名变量。
The shell uses dynamic scoping to control a variable’s visibility within functions. With dynamic scoping, visible variables and their values are a result of the sequence of function calls that caused execution to reach the current function. The value of a variable that a function sees depends on its value within its caller, if any, whether that caller is the “global” scope or another shell function. This is also the value that a local variable declaration “shadows”, and the value that is restored when the function returns.
shell使用动态作用域控制变量的可见性,变量的可见性是一系列函数调用的结果。
For example, if a variable var is declared as local in function func1, and func1 calls another function func2, references to var made from within func2 will resolve to the local variable var from func1, shadowing any global variable named var.
The following script demonstrates this behavior. When executed, the script displays
In func2, var = func1 local func1() { local var='func1 local' func2 } func2() { echo "In func2, var = $var" } var=global func1
例如,执行上述函数,func2中的var是func1中的局部变量,而如果直接调用func2,那var就是全局变量中var。
The unset builtin also acts using the same dynamic scope: if a variable is local to the current scope, unset will unset it; otherwise the unset will refer to the variable found in any calling scope as described above. If a variable at the current local scope is unset, it will remain so until it is reset in that scope or until the function returns. Once the function returns, any instance of the variable at a previous scope will become visible. If the unset acts on a variable at a previous scope, any instance of a variable with that name that had been shadowed will become visible.
unset可以让变量不可见,可以作用于动态作用域,但本函数后变量的可见性会恢复。
Function names and definitions may be listed with the -f option to the declare (typeset) builtin command (see Bash Builtins). The -F option to declare or typeset will list the function names only (and optionally the source file and line number, if the extdebug shell option is enabled). Functions may be exported so that subshells automatically have them defined with the -f option to the export builtin (see Bourne Shell Builtins).
declare -f可以列出函数名称和定义。-F选项可以只列出函数名。函数可以通过export -f导出到子shell中。
Functions may be recursive. The FUNCNEST variable may be used to limit the depth of the function call stack and restrict the number of function invocations. By default, no limit is placed on the number of recursive calls.
函数可以递归调用。可以用FUNCNEST控制递归的深度。
3.4 Shell Parameters
A parameter is an entity that stores values. It can be a name, a number, or one of the special characters listed below. A variable is a parameter denoted by a name. A variable has a value and zero or more attributes. Attributes are assigned using the declare builtin command (see the description of the declare builtin in Bash Builtins).
参数是保存值的实体,可以是名字、数字或特殊变量。变量可以拥有值、0个或更多属性。
A parameter is set if it has been assigned a value. The null string is a valid value. Once a variable is set, it may be unset only by using the unset builtin command.
空字符串是有效的值。
A variable may be assigned to by a statement of the form
讯享网name=[value]
If value is not given, the variable is assigned the null string. All values undergo tilde expansion, parameter and variable expansion, command substitution, arithmetic expansion, and quote removal (detailed below). If the variable has its integer attribute set, then value is evaluated as an arithmetic expression even if the $((…)) expansion is not used (see Arithmetic Expansion). Word splitting is not performed, with the exception of "$@" as explained below. Filename expansion is not performed. Assignment statements may also appear as arguments to the alias, declare, typeset, export, readonly, and local builtin commands (declaration commands). When in POSIX mode (see Bash POSIX Mode), these builtins may appear in a command after one or more instances of the command builtin and retain these assignment statement properties.
所有的值都会经历多种扩展。如果变量有被设置为整数(declare -i 变量名,可以通过declare -p 变量查看变量的属性,或使用declare -p列出所有变量),则即使不使用$((...))也会执行算术扩展。
In the context where an assignment statement is assigning a value to a shell variable or array index (see Arrays), the ‘+=’ operator can be used to append to or add to the variable’s previous value. This includes arguments to builtin commands such as declare that accept assignment statements (declaration commands). When ‘+=’ is applied to a variable for which the integer attribute has been set, value is evaluated as an arithmetic expression and added to the variable’s current value, which is also evaluated. When ‘+=’ is applied to an array variable using compound assignment (see Arrays), the variable’s value is not unset (as it is when using ‘=’), and new values are appended to the array beginning at one greater than the array’s maximum index (for indexed arrays), or added as additional key-value pairs in an associative array. When applied to a string-valued variable, value is expanded and appended to the variable’s value.
+=可以追加字符串,可以执行算术加法。对于复合形式的+=(例如declare -a arr1+=(4 5 6)或declare -a arr1+=("${arr2[@]}")),索引数组,对于关联数组会添加额外的键值对。
A variable can be assigned the nameref attribute using the -n option to the declare or local builtin commands (see Bash Builtins) to create a nameref, or a reference to another variable. This allows variables to be manipulated indirectly. Whenever the nameref variable is referenced, assigned to, unset, or has its attributes modified (other than using or changing the nameref attribute itself), the operation is actually performed on the variable specified by the nameref variable’s value. A nameref is commonly used within shell functions to refer to a variable whose name is passed as an argument to the function. For instance, if a variable name is passed to a shell function as its first argument, running
declare -n ref=$1
inside the function creates a nameref variable ref whose value is the variable name passed as the first argument. References and assignments to ref, and changes to its attributes, are treated as references, assignments, and attribute modifications to the variable whose name was passed as $1.
可以使用declare -n 变量1=变量2 或local -n为变量1设置nameref属性,为变量2创建引用,后续对变量1的引用、赋值、删除或更改属性都是在对变量2进行操作,除非通过unset -n或declare +n取消引用。可以通过declare -n ref=$1引用变量1(引用非位置变量不用带$)。
If the control variable in a for loop has the nameref attribute, the list of words can be a list of shell variables, and a name reference will be established for each word in the list, in turn, when the loop is executed. Array variables cannot be given the nameref attribute. However, nameref variables can reference array variables and subscripted array variables. Namerefs can be unset using the -n option to the unset builtin (see Bourne Shell Builtins). Otherwise, if unset is executed with the name of a nameref variable as an argument, the variable referenced by the nameref variable will be unset.
如果for循环中的控制变量有nameref属性,则单词列表可以是shell变量列表,在循环时依次为每个单词建立nameref。nameref变量可以引用数组变量的数组下标变量。如果unset引用变量不加-n参数,则被引用的变量(即变量2)会被删除,否则引用变量(即变量1)被删除。
3.4.1 Positional Parameters
A positional parameter is a parameter denoted by one or more digits, other than the single digit 0. Positional parameters are assigned from the shell’s arguments when it is invoked, and may be reassigned using the set builtin command. Positional parameter N may be referenced as ${N}, or as $N when N consists of a single digit. Positional parameters may not be assigned to with assignment statements. The set and shift builtins are used to set and unset them (see Shell Builtin Commands). The positional parameters are temporarily replaced when a shell function is executed (see Shell Functions).
位置参数是用数字表示的参数(不包含0)。在命令调用时从参数获取位置参数。可以通过${N}或$N引用位置参数,后者仅限于1位数。set或shift命令用于设置和取消设置。调用shell函数时位置参数会被临时替换为函数的参数。例如 set -- 1 2 3 4 表示设置4个位置参数
When a positional parameter consisting of more than a single digit is expanded, it must be enclosed in braces.
3.4.2 Special Parameters
The shell treats several parameters specially. These parameters may only be referenced; assignment to them is not allowed.
shell对几个参数特殊处理,只能引用,禁止赋值。
*( ∗ ) E x p a n d s t o t h e p o s i t i o n a l p a r a m e t e r s , s t a r t i n g f r o m o n e . W h e n t h e e x p a n s i o n i s n o t w i t h i n d o u b l e q u o t e s , e a c h p o s i t i o n a l p a r a m e t e r e x p a n d s t o a s e p a r a t e w o r d . I n c o n t e x t s w h e r e i t i s p e r f o r m e d , t h o s e w o r d s a r e s u b j e c t t o f u r t h e r w o r d s p l i t t i n g a n d f i l e n a m e e x p a n s i o n . W h e n t h e e x p a n s i o n o c c u r s w i t h i n d o u b l e q u o t e s , i t e x p a n d s t o a s i n g l e w o r d w i t h t h e v a l u e o f e a c h p a r a m e t e r s e p a r a t e d b y t h e f i r s t c h a r a c t e r o f t h e ‘ I F S ‘ s p e c i a l v a r i a b l e . T h a t i s , ‘ " *) Expands to the positional parameters, starting from one. When the expansion is not within double quotes, each positional parameter expands to a separate word. In contexts where it is performed, those words are subject to further word splitting and filename expansion. When the expansion occurs within double quotes, it expands to a single word with the value of each parameter separated by the first character of the `IFS` special variable. That is, `" ∗)Expandstothepositionalparameters,startingfromone.Whentheexpansionisnotwithindoublequotes,eachpositionalparameterexpandstoaseparateword.Incontextswhereitisperformed,thosewordsaresubjecttofurtherwordsplittingandfilenameexpansion.Whentheexpansionoccurswithindoublequotes,itexpandstoasinglewordwiththevalueofeachparameterseparatedbythefirstcharacterofthe‘IFS‘specialvariable.Thatis,‘"*“
is equivalent to”$1c$2c…", where c is the first character of the value of theIFSvariable. IfIFSis unset, the parameters are separated by spaces. IfIFS` is null, the parameters are joined without intervening separators.($*)扩展为位置参数。如果没有双引号,每个位置参数都被扩展为一个单独的单词。如果在双引号内,则会被扩展为一个单词,使用IFS变量的第一个字符分隔,如果IFS为空,则不插入分隔符。@( @ ) E x p a n d s t o t h e p o s i t i o n a l p a r a m e t e r s , s t a r t i n g f r o m o n e . I n c o n t e x t s w h e r e w o r d s p l i t t i n g i s p e r f o r m e d , t h i s e x p a n d s e a c h p o s i t i o n a l p a r a m e t e r t o a s e p a r a t e w o r d ; i f n o t w i t h i n d o u b l e q u o t e s , t h e s e w o r d s a r e s u b j e c t t o w o r d s p l i t t i n g . I n c o n t e x t s w h e r e w o r d s p l i t t i n g i s n o t p e r f o r m e d , t h i s e x p a n d s t o a s i n g l e w o r d w i t h e a c h p o s i t i o n a l p a r a m e t e r s e p a r a t e d b y a s p a c e . W h e n t h e e x p a n s i o n o c c u r s w i t h i n d o u b l e q u o t e s , a n d w o r d s p l i t t i n g i s p e r f o r m e d , e a c h p a r a m e t e r e x p a n d s t o a s e p a r a t e w o r d . T h a t i s , ‘ " @) Expands to the positional parameters, starting from one. In contexts where word splitting is performed, this expands each positional parameter to a separate word; if not within double quotes, these words are subject to word splitting. In contexts where word splitting is not performed, this expands to a single word with each positional parameter separated by a space. When the expansion occurs within double quotes, and word splitting is performed, each parameter expands to a separate word. That is, `" @)Expandstothepositionalparameters,startingfromone.Incontextswherewordsplittingisperformed,thisexpandseachpositionalparametertoaseparateword;ifnotwithindoublequotes,thesewordsaresubjecttowordsplitting.Incontextswherewordsplittingisnotperformed,thisexpandstoasinglewordwitheachpositionalparameterseparatedbyaspace.Whentheexpansionoccurswithindoublequotes,andwordsplittingisperformed,eachparameterexpandstoaseparateword.Thatis,‘"@“
is equivalent to”$1" " 2 " … ‘ . I f t h e d o u b l e − q u o t e d e x p a n s i o n o c c u r s w i t h i n a w o r d , t h e e x p a n s i o n o f t h e f i r s t p a r a m e t e r i s j o i n e d w i t h t h e b e g i n n i n g p a r t o f t h e o r i g i n a l w o r d , a n d t h e e x p a n s i o n o f t h e l a s t p a r a m e t e r i s j o i n e d w i t h t h e l a s t p a r t o f t h e o r i g i n a l w o r d . W h e n t h e r e a r e n o p o s i t i o n a l p a r a m e t e r s , ‘ " 2" …`. If the double-quoted expansion occurs within a word, the expansion of the first parameter is joined with the beginning part of the original word, and the expansion of the last parameter is joined with the last part of the original word. When there are no positional parameters, `" 2"…‘.Ifthedouble−quotedexpansionoccurswithinaword,theexpansionofthefirstparameterisjoinedwiththebeginningpartoftheoriginalword,andtheexpansionofthelastparameterisjoinedwiththelastpartoftheoriginalword.Whentherearenopositionalparameters,‘"@"and$@` expand to nothing (i.e., they are removed).($@)扩展为位置参数。在执行单词分割的上下文中,每个位置参数都被扩展为单独的词,如$@等价于"$1" "$2" ..;如果不在双引号内,这些单词会被(再次)分词,比如执行./main.sh "a b" c并在main.sh中调用./sub.sh $@,则sub.sh会收到3个参数。在不执行单词分割的上下文中,将扩展为单个单词,以空格分隔。如果双引号出现在单词内,即"ab$@cd"的形式,那么第一个位置参数会与ab相连,最后一个位置参数会与cd相连。如果没有位置参数,则$@和"$@"会被删除。#($#) Expands to the number of positional parameters in decimal.
扩展为位置参数的数量(10进制)。
?($?) Expands to the exit status of the most recently executed foreground pipeline.
最后一个前台管道的退出状态。
-($-, a hyphen.) Expands to the current option flags as specified upon invocation, by the
setbuiltin command, or those set by the shell itself (such as the -i option).$($$) Expands to the process ID of the shell. In a
()subshell, it expands to the process ID of the invoking shell, not the subshell.当前shell的进程ID。在子shell中使用
$$会得到调用外部shell的PID。!($!) Expands to the process ID of the job most recently placed into the background, whether executed as an asynchronous command or using the
bgbuiltin (see Job Control Builtins).最后一次放置到后台的作业PID。参见内置功能任务控制。
0($0) Expands to the name of the shell or shell script. This is set at shell initialization. If Bash is invoked with a file of commands (see Shell Scripts),
$0is set to the name of that file. If Bash is started with the -c option (see Invoking Bash), then$0is set to the first argument after the string to be executed, if one is present. Otherwise, it is set to the filename used to invoke Bash, as given by argument zero.shell或脚本的名称。
3.5 Shell Expansions
Expansion is performed on the command line after it has been split into tokens. There are seven kinds of expansion performed:
- brace expansion
- tilde expansion
- parameter and variable expansion
- command substitution
- arithmetic expansion
- word splitting
- filename expansion
The order of expansions is: brace expansion; tilde expansion, parameter and variable expansion, arithmetic expansion, and command substitution (done in a left-to-right fashion); word splitting; and filename expansion.
扩展的顺序是:①大括号扩展;②波浪号扩展,参数和变量扩展,算术扩展,命令替换;③单词分割;④文件名扩展。
On systems that can support it, there is an additional expansion available: process substitution. This is performed at the same time as tilde, parameter, variable, and arithmetic expansion and command substitution.
在有些系统中还支持进程替换,发生在第②步。
After these expansions are performed, quote characters present in the original word are removed unless they have been quoted themselves (quote removal).
在上述扩展完成后,引号将被删除。
Only brace expansion, word splitting, and filename expansion can increase the number of words of the expansion; other expansions expand a single word to a single word. The only exceptions to this are the expansions of "$@" and $* (see Special Parameters), and "${name[@]}" and ${name[*]} (see Arrays).
After all expansions, quote removal (see Quote Removal) is performed.
3.5.1 Brace Expansion 大括号扩展
Brace expansion is a mechanism by which arbitrary strings may be generated. This mechanism is similar to filename expansion (see Filename Expansion), but the filenames generated need not exist. Patterns to be brace expanded take the form of an optional preamble, followed by either a series of comma-separated strings or a sequence expression between a pair of braces, followed by an optional postscript. The preamble is prefixed to each string contained within the braces, and the postscript is then appended to each resulting string, expanding left to right.
大括号扩展是可以生成任意字符串的机制。形式是前置符号(可选),后面跟着一系列以逗号分隔的字符串,或一对大括号内的序列表达式,最后是后置符号(可选)。前置符号添加到每个元素前,后置符号添加到每个符号后。
Brace expansions may be nested. The results of each expanded string are not sorted; left to right order is preserved. For example,
讯享网bash$ echo a{d,c,b}e ade ace abe
A sequence expression takes the form {x..y[..incr]}, where x and y are either integers or single characters, and incr, an optional increment, is an integer. When integers are supplied, the expression expands to each number between x and y, inclusive. Supplied integers may be prefixed with ‘0’ to force each term to have the same width. When either x or y begins with a zero, the shell attempts to force all generated terms to contain the same number of digits, zero-padding where necessary. When characters are supplied, the expression expands to each character lexicographically between x and y, inclusive, using the default C locale. Note that both x and y must be of the same type. When the increment is supplied, it is used as the difference between each term. The default increment is 1 or -1 as appropriate.
序列表达式的形式是{起点..终点[..步长]},其中起点和终点是整数或单个字符,闭区间。如果提供的整数以0开头则通过填充0强制其宽度相等。如果提供字符则按照C语言环境以字典顺序扩展。默认增量是1或-1。
Brace expansion is performed before any other expansions, and any characters special to other expansions are preserved in the result. It is strictly textual. Bash does not apply any syntactic interpretation to the context of the expansion or the text between the braces.
大括号扩展在任何其他扩展之前执行,并且任何其他扩展的特殊字符都保留在结果中。 它是严格的文本。 Bash 不对扩展的上下文或大括号之间的文本应用任何句法解释。
A correctly-formed brace expansion must contain unquoted opening and closing braces, and at least one unquoted comma or a valid sequence expression. Any incorrectly formed brace expansion is left unchanged.
格式正确的大括号展开必须包含不带引号的左大括号和右大括号,以及至少一个不带引号的逗号或有效的序列表达式。 任何格式不正确的大括号扩展都保持不变。
A { or ‘,’ may be quoted with a backslash to prevent its being considered part of a brace expression. To avoid conflicts with parameter expansion, the string ‘${’ is not considered eligible for brace expansion, and inhibits brace expansion until the closing ‘}’.
{
或,可以用反斜杠转义使其不被视为表达式的一部分。为避免与参数扩展冲突,${
和}之间禁止大括号扩展。
This construct is typically used as shorthand when the common prefix of the strings to be generated is longer than in the above example:
这个结构通常用于公共前缀:
mkdir /usr/local/src/bash/{old,new,dist,bugs}
or
讯享网chown root /usr/{ucb/{ex,edit},lib/{ex?.?*,how_ex}}
3.5.2 Tilde Expansion 波浪号扩展
If a word begins with an unquoted tilde character (‘~’), all of the characters up to the first unquoted slash (or all characters, if there is no unquoted slash) are considered a tilde-prefix. If none of the characters in the tilde-prefix are quoted, the characters in the tilde-prefix following the tilde are treated as a possible login name. If this login name is the null string, the tilde is replaced with the value of the HOME shell variable. If HOME is unset, the home directory of the user executing the shell is substituted instead. Otherwise, the tilde-prefix is replaced with the home directory associated with the specified login name.
以不带引号的~开头、以不带引号的/结束的字符串称为波浪号前缀。如果波浪号前缀中没有字符被引号包围,则波浪号前缀中的字符被视为可能的登录名。如果此登录名是空串,则波浪号被替换为HOME变量。如果HOME变量未设置,则被替换为执行shell的用户的主目录。例如~表示当前用户的主目录。如果登录名不是空串,则被替换为该登录名的主目录。例如~tom表示/home/tom。
If the tilde-prefix is ‘~+’, the value of the shell variable PWD replaces the tilde-prefix. If the tilde-prefix is ‘~-’, the value of the shell variable OLDPWD, if it is set, is substituted.
~+表示PWD变量(当前目录),~-表示OLDPWD(上一个目录)
If the characters following the tilde in the tilde-prefix consist of a number N, optionally prefixed by a ‘+’ or a ‘-’, the tilde-prefix is replaced with the corresponding element from the directory stack, as it would be displayed by the dirs builtin invoked with the characters following tilde in the tilde-prefix as an argument (see The Directory Stack). If the tilde-prefix, sans the tilde, consists of a number without a leading ‘+’ or ‘-’, ‘+’ is assumed.
$N表示目录栈的第N个元素,将由内置命令dirs显示。目录栈的内容是通过pushd和popd手工记录的。
If the login name is invalid, or the tilde expansion fails, the word is left unchanged.
Each variable assignment is checked for unquoted tilde-prefixes immediately following a ‘:’ or the first ‘=’. In these cases, tilde expansion is also performed. Consequently, one may use filenames with tildes in assignments to PATH, MAILPATH, and CDPATH, and the shell assigns the expanded value.
在给PATH进行赋值时也可以使用~,会对:或=后面的~进行检查。
The following table shows how Bash treats unquoted tilde-prefixes:
~The value of
$HOME~/foo$HOME/foo
~fred/fooThe subdirectory
fooof the home directory of the userfred~+/foo$PWD/foo
~-/foo${OLDPWD-‘~-’}/foo
~NThe string that would be displayed by ‘dirs +N’
~+NThe string that would be displayed by ‘dirs +N’
~-NThe string that would be displayed by ‘dirs -N’
Bash also performs tilde expansion on words satisfying the conditions of variable assignments (see Shell Parameters) when they appear as arguments to simple commands. Bash does not do this, except for the declaration commands listed above, when in POSIX mode.
Bash会为 满足变量赋值条件的单词 以简单命令的参数出现时 进行波浪号替换。
3.5.3 Shell Parameter Expansion 参数扩展
The ‘$’ character introduces parameter expansion, command substitution, or arithmetic expansion. The parameter name or symbol to be expanded may be enclosed in braces, which are optional but serve to protect the variable to be expanded from characters immediately following it which could be interpreted as part of the name.
$字符引入了参数扩展、命令替换或算术替换。大括号可以保护要扩展的变量免受其后面字符的影响,否则后面的字符可能解释为名称的一部分。
When braces are used, the matching ending brace is the first ‘}’ not escaped by a backslash or within a quoted string, and not within an embedded arithmetic expansion, command substitution, or parameter expansion.
匹配的大括号是不能被\转义或在引号内或在嵌入的算术扩展、命令替换或参数扩展中。
The basic form of parameter expansion is ${parameter}. The value of parameter is substituted. The parameter is a shell parameter as described above (see Shell Parameters) or an array reference (see Arrays). The braces are required when parameter is a positional parameter with more than one digit, or when parameter is followed by a character that is not to be interpreted as part of its name.
参数扩展的基本形式的${参数},这一部分被替换为参数的值。
If the first character of parameter is an exclamation point (!), and parameter is not a nameref, it introduces a level of indirection. Bash uses the value formed by expanding the rest of parameter as the new parameter; this is then expanded and that value is used in the rest of the expansion, rather than the expansion of the original parameter. This is known as indirect expansion. The value is subject to tilde expansion, parameter expansion, command substitution, and arithmetic expansion. If parameter is a nameref, this expands to the name of the variable referenced by parameter instead of performing the complete indirect expansion. The exceptions to this are the expansions of ${!prefix*} and ${!name[@]} described below. The exclamation point must immediately follow the left brace in order to introduce indirection.
!参数表示间接扩展。比如假设a='1',b='a',则${!b}=1。Bash使用参数的值作为新参数,并对新参数进行展开用于后续扩展。!nameref将扩展为引用的变量的名称,而非间接扩展。
In each of the cases below, word is subject to tilde expansion, parameter expansion, command substitution, and arithmetic expansion.
在下面的例子中,单词会经历波浪线扩展、参数扩展、命令替换和算术扩展。
When not performing substring expansion, using the form described below (e.g., ‘:-’), Bash tests for a parameter that is unset or null. Omitting the colon results in a test only for a parameter that is unset. Put another way, if the colon is included, the operator tests for both parameter’s existence and that its value is not null; if the colon is omitted, the operator tests only for existence.
${parameter:-word}If parameter is unset or null, the expansion of word is substituted. Otherwise, the value of parameter is substituted.
${参数:-单词}如果参数未设置或为空,则替换为单词的扩展,否则替换为参数的值。${parameter:=word}If parameter is unset or null, the expansion of word is assigned to parameter. The value of parameter is then substituted. Positional parameters and special parameters may not be assigned to in this way.
${参数:=单词}如果参数未设置或为空,则单词的扩展被赋给参数,然后被替换为参数的值。位置参数和特殊参数不能用这种方式设置。${parameter:?word}If parameter is null or unset, the expansion of word (or a message to that effect if word is not present) is written to the standard error and the shell, if it is not interactive, exits. Otherwise, the value of parameter is substituted.
${参数:?单词}如果参数为空或未设置,单词的扩展被输出到标准错误中,且shell退出。否则替换为参数。${parameter:+word}If parameter is null or unset, nothing is substituted, otherwise the expansion of word is substituted.
${参数:+单词}如果参数为空或未设置,则替换为空串。否则替换为单词的扩展。${parameter:offset}${parameter:offset:length}${参数:偏移量[:长度]}This is referred to as Substring Expansion. It expands to up to length characters of the value of parameter starting at the character specified by offset. If parameter is ‘@’, an indexed array subscripted by ‘
@’ or ‘*’, or an associative array name, the results differ as described below. If length is omitted, it expands to the substring of the value of parameter starting at the character specified by offset and extending to the end of the value. length and offset are arithmetic expressions (see Shell Arithmetic).从参数的
偏移量开始提取最多长度个字符。如果参数是@,或以@或*为下标的索引数组,或关联数组则结果不一样。If offset evaluates to a number less than zero, the value is used as an offset in characters from the end of the value of parameter. If length evaluates to a number less than zero, it is interpreted as an offset in characters from the end of the value of parameter rather than a number of characters, and the expansion is the characters between offset and that result. Note that a negative offset must be separated from the colon by at least one space to avoid being confused with the ‘:-’ expansion.
如果
偏移量是负数,表示从参数值末尾开始的字符偏移量,如果长度是负数,表示距参数末尾的偏移量而非字符数。负偏移量和冒号之间必须有空格。Here are some examples illustrating substring expansion on parameters and subscripted arrays:
$ string=0abcdefgh $ echo ${string:7} 7890abcdefgh $ echo ${string:7:0} $ echo ${string:7:2} 78 $ echo ${string:7:-2} 7890abcdef $ echo ${string: -7} bcdefgh $ echo ${string: -7:0} $ echo ${string: -7:2} bc $ echo ${string: -7:-2} bcdef $ set -- 0abcdefgh $ echo ${1:7} 7890abcdefgh $ echo ${1:7:0} $ echo ${1:7:2} 78 $ echo ${1:7:-2} 7890abcdef $ echo ${1: -7} bcdefgh $ echo ${1: -7:0} $ echo ${1: -7:2} bc $ echo ${1: -7:-2} bcdef $ array[0]=0abcdefgh $ echo ${array[0]:7} 7890abcdefgh $ echo ${array[0]:7:0} $ echo ${array[0]:7:2} 78 $ echo ${array[0]:7:-2} 7890abcdef $ echo ${array[0]: -7} bcdefgh $ echo ${array[0]: -7:0} $ echo ${array[0]: -7:2} bc $ echo ${array[0]: -7:-2} bcdefIf parameter is ‘@’, the result is length positional parameters beginning at offset. A negative offset is taken relative to one greater than the greatest positional parameter, so an offset of -1 evaluates to the last positional parameter. It is an expansion error if length evaluates to a number less than zero.
如果
参数是@,那么结果是以偏移量为起点的长度个位置参数。The following examples illustrate substring expansion using positional parameters:
讯享网
$ set -- 1 2 3 4 5 6 7 8 9 0 a b c d e f g h $ echo ${@:7} 7 8 9 0 a b c d e f g h $ echo ${@:7:0} $ echo ${@:7:2} 7 8 $ echo ${@:7:-2} bash: -2: substring expression < 0 $ echo ${@: -7:2} b c $ echo ${@:0} ./bash 1 2 3 4 5 6 7 8 9 0 a b c d e f g h $ echo ${@:0:2} ./bash 1 $ echo ${@: -7:0}If parameter is an indexed array name subscripted by ‘@’ or ‘*’, the result is the length members of the array beginning with
${parameter[offset]}. A negative offset is taken relative to one greater than the maximum index of the specified array. It is an expansion error if length evaluates to a number less than zero.These examples show how you can use substring expansion with indexed arrays:
$ array=(0 1 2 3 4 5 6 7 8 9 0 a b c d e f g h) $ echo ${array[@]:7} 7 8 9 0 a b c d e f g h $ echo ${array[@]:7:2} 7 8 $ echo ${array[@]: -7:2} b c $ echo ${array[@]: -7:-2} bash: -2: substring expression < 0 $ echo ${array[@]:0} 0 1 2 3 4 5 6 7 8 9 0 a b c d e f g h $ echo ${array[@]:0:2} 0 1 $ echo ${array[@]: -7:0}Substring expansion applied to an associative array produces undefined results.
子序列操作不支持关联数组。
Substring indexing is zero-based unless the positional parameters are used, in which case the indexing starts at 1 by default. If offset is 0, and the positional parameters are used,
$0is prefixed to the list.${!prefix*}${!prefix@}Expands to the names of variables whose names begin with prefix, separated by the first character of the
IFSspecial variable. When ‘@’ is used and the expansion appears within double quotes, each variable name expands to a separate word.${!前缀*} ${!前缀@}列出所有以前缀开头的变量名。如果使用@并且用双引号包围,每个变量名都扩展为单独的单词。${!name[@]}${!name[*]}If name is an array variable, expands to the list of array indices (keys) assigned in name. If name is not an array, expands to 0 if name is set and null otherwise. When ‘@’ is used and the expansion appears within double quotes, each key expands to a separate word.
${!变量[@]} ${!变量[*]}如果变量是数组,则扩展为变量中的索引(键)列表。如果使用了@和双引号,则每个索引都扩展为单独的单词。${#parameter}The length in characters of the expanded value of parameter is substituted. If parameter is ‘’ or ‘@’, the value substituted is the number of positional parameters. If parameter is an array name subscripted by ‘’ or ‘@’, the value substituted is the number of elements in the array. If parameter is an indexed array name subscripted by a negative number, that number is interpreted as relative to one greater than the maximum index of parameter, so negative indices count back from the end of the array, and an index of -1 references the last element.
${#参数}扩展为参数对应值的字符串长度。如果参数是数组[*]或[@]则为元素个数。${parameter#word}${parameterword}The word is expanded to produce a pattern and matched according to the rules described below (see Pattern Matching). If the pattern matches the beginning of the expanded value of parameter, then the result of the expansion is the expanded value of parameter with the shortest matching pattern (the ‘#’ case) or the longest matching pattern (the ‘’ case) deleted. If parameter is ‘@’ or ‘’, the pattern removal operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with ‘@’ or ‘’, the pattern removal operation is applied to each member of the array in turn, and the expansion is the resultant list.
${参数#单词}${参数单词}单词被扩展为模式,如果参数的值与单词的开头匹配(# 最短匹配 最长匹配),则将其删除。如果参数是@ 或*则或参数是数组[@/*]则将删除操作依次应用于每个成员。${parameter%word}${parameter%%word}The word is expanded to produce a pattern and matched according to the rules described below (see Pattern Matching). If the pattern matches a trailing portion of the expanded value of parameter, then the result of the expansion is the value of parameter with the shortest matching pattern (the ‘%’ case) or the longest matching pattern (the ‘%%’ case) deleted. If parameter is ‘@’ or ‘’, the pattern removal operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with ‘@’ or ‘’, the pattern removal operation is applied to each member of the array in turn, and the expansion is the resultant list.
${参数%单词}${参数%%单词}与上面类似,但是改成了末尾匹配。${parameter/pattern/string}The pattern is expanded to produce a pattern just as in filename expansion. Parameter is expanded and the longest match of pattern against its value is replaced with string. The match is performed according to the rules described below (see Pattern Matching). If pattern begins with ‘/’, all matches of pattern are replaced with string. Normally only the first match is replaced. If pattern begins with ‘#’, it must match at the beginning of the expanded value of parameter. If pattern begins with ‘%’, it must match at the end of the expanded value of parameter. If string is null, matches of pattern are deleted and the
/following pattern may be omitted. If thenocasematchshell option (see the description ofshoptin The Shopt Builtin) is enabled, the match is performed without regard to the case of alphabetic characters. If parameter is ‘@’ or ‘*’, the substitution operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with ‘@’ or ‘*’, the substitution operation is applied to each member of the array in turn, and the expansion is the resultant list.${参数/模式/字符串}参数按照模式的最长匹配被替换为字符串。如果模式以/开头,则所有模式都被替换,默认只替换每一个。如果模式以#开头,则必须匹配参数的开头,如果模式以%开头,则必须匹配参数末尾。可以通过shopt控制大小写敏感。如果参数是@或*或数组则对每个成员都进行替换。${parameter^pattern}${parameter^^pattern}${parameter,pattern}${parameter,,pattern}This expansion modifies the case of alphabetic characters in parameter. The pattern is expanded to produce a pattern just as in filename expansion. Each character in the expanded value of parameter is tested against pattern, and, if it matches the pattern, its case is converted. The pattern should not attempt to match more than one character. The ‘^’ operator converts lowercase letters matching pattern to uppercase; the ‘,’ operator converts matching uppercase letters to lowercase. The ‘^^’ and ‘,’ expansions convert each matched character in the expanded value; the ‘^’ and ‘,’ expansions match and convert only the first character in the expanded value. If pattern is omitted, it is treated like a ‘?’, which matches every character. If parameter is ‘@’ or ‘
*’, the case modification operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with ‘@’ or ‘*’, the case modification operation is applied to each member of the array in turn, and the expansion is the resultant list.${参数^模式}${参数^^模式}${参数,模式}${参数,,模式}将匹配模式的参数的值修改大小写。^改为大写,,改为小写,只修改第一次出现,^^和,,修改所有匹配。${parameter@operator}{参数@操作}The expansion is either a transformation of the value of parameter or information about parameter itself, depending on the value of operator. Each operator is a single letter:
要么是参数值的转换,要么是参数本身的信息。
UThe expansion is a string that is the value of parameter with lowercase alphabetic characters converted to uppercase. 将小写字母转换为大写。uThe expansion is a string that is the value of parameter with the first character converted to uppercase, if it is alphabetic. 将第一个字符改成大写。LThe expansion is a string that is the value of parameter with uppercase alphabetic characters converted to lowercase. 将大写字母转换成小写。QThe expansion is a string that is the value of parameter quoted in a format that can be reused as input. 将参数的值用引号括起来,以便用于输入。EThe expansion is a string that is the value of parameter with backslash escape sequences expanded as with the$'…'quoting mechanism. ‘…’ quoting mechanism. 将字符串按照C语言标准的反斜杠进行转义,就像使用’…'一样。PThe expansion is a string that is the result of expanding the value of parameter as if it were a prompt string (see Controlling the Prompt).AThe expansion is a string in the form of an assignment statement ordeclarecommand that, if evaluated, will recreate parameter with its attributes and value. 扩展为赋值或声明形式的字符串。KProduces a possibly-quoted version of the value of parameter, except that it prints the values of indexed and associative arrays as a sequence of quoted key-value pairs (see Arrays).aThe expansion is a string consisting of flag values representing parameter’s attributes.If parameter is ‘@’ or ‘
*’, the operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with ‘@’ or ‘*’, the operation is applied to each member of the array in turn, and the expansion is the resultant list.The result of the expansion is subject to word splitting and filename expansion as described below.
3.5.4 Command Substitution 命令替换
Command substitution allows the output of a command to replace the command itself. Command substitution occurs when a command is enclosed as follows:
命令替换可以使用命令的输出替换命令本身:
讯享网$(command)
or
`command`
Bash performs the expansion by executing command in a subshell environment and replacing the command substitution with the standard output of the command, with any trailing newlines deleted. Embedded newlines are not deleted, but they may be removed during word splitting. The command substitution $(cat file) can be replaced by the equivalent but faster $(< file).
命令替换可以在子shell中执行命令并将命令替换为命令的标准输出。
When the old-style backquote form of substitution is used, backslash retains its literal meaning except when followed by $, ` or \. The first backquote not preceded by a backslash terminates the command substitution. When using the $(command) form, all characters between the parentheses make up the command; none are treated specially.
当使用旧式反引号的替换时,反斜杠在$ `或\前面不保留字面含义。当使用$(命令)形式时,括号之间的所有字符组成命令。
Command substitutions may be nested. To nest when using the backquoted form, escape the inner backquotes with backslashes.
命令替换可能是嵌套的,要在使用反引号形式的嵌套,请使用反斜杠转义内部反引号。
If the substitution appears within double quotes, word splitting and filename expansion are not performed on the results.
3.5.5 Arithmetic Expansion 算术扩展
Arithmetic expansion allows the evaluation of an arithmetic expression and the substitution of the result. The format for arithmetic expansion is:
讯享网$(( expression ))
The expression is treated as if it were within double quotes, but a double quote inside the parentheses is not treated specially. All tokens in the expression undergo parameter and variable expansion, command substitution, and quote removal. The result is treated as the arithmetic expression to be evaluated. Arithmetic expansions may be nested.
表达式被视为在双引号内,但括号内的双引号不会被特殊处理。 表达式中的所有标记都经过参数和变量扩展、命令替换和引号删除。 结果被视为要计算的算术表达式。 算术扩展可以嵌套。
The evaluation is performed according to the rules listed below (see Shell Arithmetic). If the expression is invalid, Bash prints a message indicating failure to the standard error and no substitution occurs.
3.5.6 Process Substitution 进程替换
Process substitution allows a process’s input or output to be referred to using a filename. It takes the form of
<(list)
or
讯享网>(list)
进程替换允许通过文件名访问进程的输入或输出,它的形式是<(列表)或>(列表)。
The process list is run asynchronously, and its input or output appears as a filename. This filename is passed as an argument to the current command as the result of the expansion. If the >(list) form is used, writing to the file will provide input for list. If the <(list) form is used, the file passed as an argument should be read to obtain the output of list. Note that no space may appear between the < or > and the left parenthesis, otherwise the construct would be interpreted as a redirection. Process substitution is supported on systems that support named pipes (FIFOs) or the /dev/fd method of naming open files.
列表是一个可以生成列表的进程,例如ls。列表的输入或输出作为文件名返回,文件名作为参数传递给当前命令。若使用>(列表)形式,向文件写入数据会为列表提供输入。若使用<(列表)形式,则可以从列表中读取输出。注意<和(之间不能有空格,否则会当作重定向。
例如echo <(ls)会输出一个临时文件名/dev/fd/63。cat 文件名会显示文件内容,所以cat <(ls)会打印ls输出的内容。tee 文件名会读取输入并将结果写到文件和屏幕上,所以tee >(cat)可以将内容在屏幕上显示两次。
When available, process substitution is performed simultaneously with parameter and variable expansion, command substitution, and arithmetic expansion.
进程替换与参数变量扩展、命令替换和算术扩展同时执行。
3.5.7 Word Splitting 单词分割
The shell scans the results of parameter expansion, command substitution, and arithmetic expansion that did not occur within double quotes for word splitting.
双引号会扫描上面的扩展的结果并分词,除非结果在双引号内。
The shell treats each character of $IFS as a delimiter, and splits the results of the other expansions into words using these characters as field terminators. If IFS is unset, or its value is exactly <space><tab><newline>, the default, then sequences of <space>, <tab>, and <newline> at the beginning and end of the results of the previous expansions are ignored, and any sequence of IFS characters not at the beginning or end serves to delimit words. If IFS has a value other than the default, then sequences of the whitespace characters space, tab, and newline are ignored at the beginning and end of the word, as long as the whitespace character is in the value of IFS (an IFS whitespace character). Any character in IFS that is not IFS whitespace, along with any adjacent IFS whitespace characters, delimits a field. A sequence of IFS whitespace characters is also treated as a delimiter. If the value of IFS is null, no word splitting occurs.
Shell将IFS中的每个单词都当作分隔符,对扩展的结果进行字符串分割。IFS的默认值是<空格><换行>。如果IFS的值为空,则不进行分词。
Explicit null arguments ("" or '') are retained and passed to commands as empty strings. Unquoted implicit null arguments, resulting from the expansion of parameters that have no values, are removed. If a parameter with no value is expanded within double quotes, a null argument results and is retained and passed to a command as an empty string. When a quoted null argument appears as part of a word whose expansion is non-null, the null argument is removed. That is, the word -d'' becomes -d after word splitting and null argument removal.
显式的空参数会被保留,作为空参数会给命令。由之前的扩展导致的不带引号的空参数会被删除。当带引号的空参数作为单词的一部分时,空参数会被删除,例如-d''变成-d,ab""变成ab。
Note that if no expansion occurs, no splitting is performed.
如果不发生扩展则不进行单词分割。
3.5.8 Filename Expansion 文件名扩展
After word splitting, unless the -f option has been set (see The Set Builtin), Bash scans each word for the characters ‘*’, ‘?’, and ‘[’. If one of these characters appears, and is not quoted, then the word is regarded as a pattern, and replaced with an alphabetically sorted list of filenames matching the pattern (see Pattern Matching). If no matching filenames are found, and the shell option nullglob is disabled, the word is left unchanged. If the nullglob option is set, and no matches are found, the word is removed. If the failglob shell option is set, and no matches are found, an error message is printed and the command is not executed. If the shell option nocaseglob is enabled, the match is performed without regard to the case of alphabetic characters.
没有引号包围的* ? [会被替换为匹配的文件名列表。如果没有找到匹配的则不替换。可以使用set -f禁用文件名扩展。
When a pattern is used for filename expansion, the character ‘.’ at the start of a filename or immediately following a slash must be matched explicitly, unless the shell option dotglob is set. The filenames ‘.’ and ‘…’ must always be matched explicitly, even if dotglob is set. In other cases, the ‘.’ character is not treated specially.
文件名开头或紧跟在斜杠后的.必须明确匹配。文件名.和..必须明确匹配。也就是*不能匹配.和..,*fig不能匹配.config。
When matching a filename, the slash character must always be matched explicitly by a slash in the pattern, but in other matching contexts it can be matched by a special pattern character as described below (see Pattern Matching).
文件名中的/必须明确匹配,但在其它匹配上下文中可以由特殊模式字符匹配。
See the description of shopt in The Shopt Builtin, for a description of the nocaseglob, nullglob, failglob, and dotglob options.
nocaseglob可以使文件名大小写不敏感,使用nullglob在找不到匹配选项时替换为空串,failglob可以在不匹配时打印错误,dotglob可以允许匹配文件名开头的.。通过shopt -s dotglob启动.匹配,就可以使用du -sh *统计隐藏文件的信息。
The GLOBIGNORE shell variable may be used to restrict the set of file names matching a pattern. If GLOBIGNORE is set, each matching file name that also matches one of the patterns in GLOBIGNORE is removed from the list of matches. If the nocaseglob option is set, the matching against the patterns in GLOBIGNORE is performed without regard to case. The filenames . and … are always ignored when GLOBIGNORE is set and not null. However, setting GLOBIGNORE to a non-null value has the effect of enabling the dotglob shell option, so all other filenames beginning with a ‘.’ will match. To get the old behavior of ignoring filenames beginning with a ‘.’, make ‘.*’ one of the patterns in GLOBIGNORE. The dotglob option is disabled when GLOBIGNORE is unset.
GLOBIGNORE变量可以屏蔽符合该模式的文件。
3.5.8.1 Pattern Matching
Any character that appears in a pattern, other than the special pattern characters described below, matches itself. The NUL character may not occur in a pattern. A backslash escapes the following character; the escaping backslash is discarded when matching. The special pattern characters must be quoted if they are to be matched literally.
反斜杠可以对下面的特殊符号转义,匹配时会丢掉反斜杠,如果要按字面匹配,则必须用引号包围特殊字符。
The special pattern characters have the following meanings:
*Matches any string, including the null string. When the
globstarshell option is enabled, and ‘*’ is used in a filename expansion context, two adjacent ‘*’s used as a single pattern will match all files and zero or more directories and subdirectories. If followed by a ‘/’, two adjacent ‘*’s will match only directories and subdirectories.匹配任何字符串,包括空串。如果打开globstar选项,则
可以匹配所有文件及多个目录,/只匹配目录。?Matches any single character.
匹配任意单个字符。
[…]Matches any one of the enclosed characters. A pair of characters separated by a hyphen denotes a range expression; any character that falls between those two characters, inclusive, using the current locale’s collating sequence and character set, is matched. If the first character following the ‘[’ is a ‘!’ or a ‘^’ then any character not enclosed is matched. A ‘-’ may be matched by including it as the first or last character in the set. A ‘]’ may be matched by including it as the first character in the set. The sorting order of characters in range expressions is determined by the current locale and the values of the
LC_COLLATEandLC_ALLshell variables, if set.匹配任何一个包含的字符。可以使用
-表示字符范围。如果[后的第一个字符是!或^,则表示匹配求包含的字符。可以将]作为集合中的第一个字符来匹配]。For example, in the default C locale, ‘[a-dx-z]’ is equivalent to ‘[abcdxyz]’. Many locales sort characters in dictionary order, and in these locales ‘[a-dx-z]’ is typically not equivalent to ‘[abcdxyz]’; it might be equivalent to ‘[aBbCcDdxXyYz]’, for example. To obtain the traditional interpretation of ranges in bracket expressions, you can force the use of the C locale by setting the
LC_COLLATEorLC_ALLenvironment variable to the value ‘C’, or enable theglobasciirangesshell option.在默认的C语言环境中,[a-dx-y]表示[abcdxyz],在字典顺序环境中可能等同于
[aBbCcDdxXyYz]。Within ‘[’ and ‘]’, character classes can be specified using the syntax
[:class:], where class is one of the following classes defined in the POSIX standard:可以使用
[:类别:]指定字符类别。alnum alpha ascii blank cntrl digit graph lower print punct space upper word xdigitA character class matches any character belonging to that class. The
wordcharacter class matches letters, digits, and the character ‘_’.word类别可以匹配
字母、数字和_。Within ‘[’ and ‘]’, an equivalence class can be specified using the syntax
[=c=], which matches all characters with the same collation weight (as defined by the current locale) as the character c.可以使用[=c=]指定等价类,匹配与字符c具有相同排序权重的所有字符。
Within ‘[’ and ‘]’, the syntax
[.symbol.]matches the collating symbol symbol.
If the extglob shell option is enabled using the shopt builtin, several extended pattern matching operators are recognized. In the following description, a pattern-list is a list of one or more patterns separated by a ‘|’. Composite patterns may be formed using one or more of the following sub-patterns:
如果通过shopt打开了extglob选项,则可以更多扩展模式运算符。
?(pattern-list)Matches zero or one occurrence of the given patterns.
匹配0或1次给定的模式。
*(pattern-list)Matches zero or more occurrences of the given patterns.
匹配0或多次给定的模式。
+(pattern-list)Matches one or more occurrences of the given patterns.
匹配1或多次给定的模式。
@(pattern-list)Matches one of the given patterns.
匹配给定的模式之一。
!(pattern-list)Matches anything except one of the given patterns.
匹配任何不满足模式的内容。
Complicated extended pattern matching against long strings is slow, especially when the patterns contain alternations and the strings contain multiple matches. Using separate matches against shorter strings, or using arrays of strings instead of a single long string, may be faster.
针对长字符串的复杂扩展模式匹配速度很慢。
3.5.9 Quote Removal 引号移除
After the preceding expansions, all unquoted occurrences of the characters ‘\’, ‘'’, and ‘"’ that did not result from one of the above expansions are removed.
所有不带引号的且不由上述扩展产生的\ '和"都会被删除。
3.6 Redirections
Before a command is executed, its input and output may be redirected using a special notation interpreted by the shell. Redirection allows commands’ file handles to be duplicated, opened, closed, made to refer to different files, and can change the files the command reads from and writes to. Redirection may also be used to modify file handles in the current shell execution environment. The following redirection operators may precede or appear anywhere within a simple command or may follow a command. Redirections are processed in the order they appear, from left to right.
重定向可以将命令的文件句柄被复制、打开、关闭、指向不同文件,可以更改命令读取和写入的文件。重定向也可以用于修改当前shell执行环境中的文件句柄。重定向可以出现在简单命令的任何地方,重定向按照出现的顺序处理。
Each redirection that may be preceded by a file descriptor number may instead be preceded by a word of the form {varname}. In this case, for each redirection operator except >&- and <&-, the shell will allocate a file descriptor greater than 10 and assign it to {varname}. If >&- or <&- is preceded by {varname}, the value of varname defines the file descriptor to close. If {varname} is supplied, the redirection persists beyond the scope of the command, allowing the shell programmer to manage the file descriptor’s lifetime manually.
重定向符前的文件描述符(fd)编号可以被替换为{变量名}的形式。因此,对于除了>&-和<&-的任何重定向符号,shell会分配一个大于10的fd并将其分配给变量名。如果>&-和<&-位于{变量名}之前,则变量名定义了一个要关闭的fd。如果提供了变量名,则重定向会超出命令的的范围,允许手动管理fd的生命周期。
In the following descriptions, if the file descriptor number is omitted, and the first character of the redirection operator is ‘<’, the redirection refers to the standard input (file descriptor 0). If the first character of the redirection operator is ‘>’, the redirection refers to the standard output (file descriptor 1).
在下面的描述中,如果重定向运算符的第一个字符是<且省略fd编号,则fd为0(标准输入)。如果第一个字符是>,则fd为1(标准输出)。
The word following the redirection operator in the following descriptions, unless otherwise noted, is subjected to brace expansion, tilde expansion, parameter expansion, command substitution, arithmetic expansion, quote removal, filename expansion, and word splitting. If it expands to more than one word, Bash reports an error.
重定向后面的单词会经历多种扩展,且扩展的结果不能是多个单词。
Note that the order of redirections is significant. For example, the command
ls > dirlist 2>&1
directs both standard output (file descriptor 1) and standard error (file descriptor 2) to the file dirlist, while the command
讯享网ls 2>&1 > dirlist
directs only the standard output to file dirlist, because the standard error was made a copy of the standard output before the standard output was redirected to dirlist.
重定向的顺序很重要,例如ls > 文件 2>&1会将标准输出和标准错误定向到文件。而ls 2>&1 > 文件只将标准输出定向到文件,因为标准错误成为标准输出的拷贝是在标准输出定向到文件之前完成的。
Bash handles several filenames specially when they are used in redirections, as described in the following table. If the operating system on which Bash is running provides these special files, bash will use them; otherwise it will emulate them internally with the behavior described below.
Bash会对在重定向时对如下的文件名作特殊处理。如果操作系统提供了这些文件,则直接使用操作系统提供的,否则bash会模拟这些行为。
/dev/fd/fdIf fd is a valid integer, file descriptor fd is duplicated.
is duplicated. 复制fd所代表的文件描述符。
/dev/stdinFile descriptor 0 is duplicated.
/dev/stdoutFile descriptor 1 is duplicated.
/dev/stderrFile descriptor 2 is duplicated.
/dev/tcp/host/portIf host is a valid hostname or Internet address, and port is an integer port number or service name, Bash attempts to open the corresponding TCP socket.
尝试打开
host:port指定的TCP连接。/dev/udp/host/portIf host is a valid hostname or Internet address, and port is an integer port number or service name, Bash attempts to open the corresponding UDP socket.
尝试打开
host:port指定的UDP连接。
A failure to open or create a file causes the redirection to fail.
打开文件出现错误会导致重定向失败。
Redirections using file descriptors greater than 9 should be used with care, as they may conflict with file descriptors the shell uses internally.
大于9的fd可能与shell内部的fd冲突。
3.6.1 Redirecting Input 重定向输入
Redirection of input causes the file whose name results from the expansion of word to be opened for reading on file descriptor n, or the standard input (file descriptor 0) if n is not specified.
输入的重定向会导致打开由word扩展到的文件名,用于读取。默认值是0。
The general format for redirecting input is:
[n]<word
3.6.2 Redirecting Output 重定向输出
Redirection of output causes the file whose name results from the expansion of word to be opened for writing on file descriptor n, or the standard output (file descriptor 1) if n is not specified. If the file does not exist it is created; if it does exist it is truncated to zero size.
打开word指定的文件名用于读取。如果文件不存在会被创建,如果文件存在其内容会被清空。
The general format for redirecting output is:
讯享网[n]>[|]word
If the redirection operator is ‘>’, and the noclobber option to the set builtin has been enabled, the redirection will fail if the file whose name results from the expansion of word exists and is a regular file. If the redirection operator is ‘>|’, or the redirection operator is ‘>’ and the noclobber option is not enabled, the redirection is attempted even if the file named by word exists.
noclobber选项和>|都可以用于禁止覆盖普通文件。
3.6.3 Appending Redirected Output 追加重定向输出
Redirection of output in this fashion causes the file whose name results from the expansion of word to be opened for appending on file descriptor n, or the standard output (file descriptor 1) if n is not specified. If the file does not exist it is created.
The general format for appending output is:
[n]>>word
将文件描述符n的内容追加到word代表的文件中,如果文件不存在则创建。
3.6.4 Redirecting Standard Output and Standard Error 重定向标准输出和标准错误
This construct allows both the standard output (file descriptor 1) and the standard error output (file descriptor 2) to be redirected to the file whose name is the expansion of word.
这种方式将标准输出和错误都重定向到文件。
There are two formats for redirecting standard output and standard error:
讯享网&>word
and
>&word
Of the two forms, the first is preferred. This is semantically equivalent to
讯享网>word 2>&1
When using the second form, word may not expand to a number or ‘-’. If it does, other redirection operators apply (see Duplicating File Descriptors below) for compatibility reasons.
两种形式中更推荐第一种。因为在使用第二种形式时,word不能扩展为数字或-。
3.6.5 Appending Standard Output and Standard Error 追加标准输出和标准错误
This construct allows both the standard output (file descriptor 1) and the standard error output (file descriptor 2) to be appended to the file whose name is the expansion of word.
The format for appending standard output and standard error is:
&>>word
This is semantically equivalent to
讯享网>>word 2>&1
(see Duplicating File Descriptors below).
3.6.6 Here Documents 嵌入文档
This type of redirection instructs the shell to read input from the current source until a line containing only word (with no trailing blanks) is seen. All of the lines read up to that point are then used as the standard input (or file descriptor n if n is specified) for a command.
让shell从当前源读取输入,直到看见只包含单词的行(不能有尾随的空格),然后该行之前的内容作为标准输入(或输入到指定的文件描述符中)。
The format of here-documents is:
[n]<<[-]word here-document delimiter
No parameter and variable expansion, command substitution, arithmetic expansion, or filename expansion is performed on word. If any part of word is quoted, the delimiter is the result of quote removal on word, and the lines in the here-document are not expanded. If word is unquoted, all lines of the here-document are subjected to parameter expansion, command substitution, and arithmetic expansion, the character sequence \newline is ignored, and ‘\’ must be used to quote the characters ‘\’, ‘$’, and ‘`’.
不会对单词执行参数和变量扩展、命令替换、算术扩展和文件名扩展,但执行引号移除。如果单词中或周围有引号,则嵌入文档不执行扩展。如果单词无引号,则嵌入文档中的每一行都会执行参数扩展、命令替换和算术扩展,换行符被忽略,必须使用\对\ $和`进行转义。
If the redirection operator is ‘<<-’, then all leading tab characters are stripped from input lines and the line containing delimiter. This allows here-documents within shell scripts to be indented in a natural fashion.
如果重定向是<<-,则所有输入行开头的制表符都将删除。
3.6.7 Here Strings 嵌入字符串
A variant of here documents, the format is:
讯享网[n]<<< word
嵌入文档的变体是嵌入字符串,格式是[n]<<< 单词
The word undergoes tilde expansion, parameter and variable expansion, command substitution, arithmetic expansion, and quote removal. Filename expansion and word splitting are not performed. The result is supplied as a single string, with a newline appended, to the command on its standard input (or file descriptor n if n is specified).
单词会经历多种扩展,但不执行文件名扩展和单词扩展,结果以单个字符串加换行符的形式提供,输入到标准输入中。
3.6.8 Duplicating File Descriptors 复制文件描述符
The redirection operator
[n]<&word
is used to duplicate input file descriptors. If word expands to one or more digits, the file descriptor denoted by n is made to be a copy of that file descriptor. If the digits in word do not specify a file descriptor open for input, a redirection error occurs. If word evaluates to ‘-’, file descriptor n is closed. If n is not specified, the standard input (file descriptor 0) is used.
重定向操作符[n]<&单词用于复制输入fd,如果单词扩展为1或多个数字,则n表示的fd成为上述fd的副本。如果单词是-,则关闭fd。
The operator
讯享网[n]>&word
is used similarly to duplicate output file descriptors. If n is not specified, the standard output (file descriptor 1) is used. If the digits in word do not specify a file descriptor open for output, a redirection error occurs. If word evaluates to ‘-’, file descriptor n is closed. As a special case, if n is omitted, and word does not expand to one or more digits or ‘-’, the standard output and standard error are redirected as described previously.
[n]>&单词用于复制输出fd。如果省略n且单词不是数字或-,则会被输出到单词对应的文件中。
3.6.9 Moving File Descriptors
The redirection operator
[n]<&digit-
moves the file descriptor digit to file descriptor n, or the standard input (file descriptor 0) if n is not specified. digit is closed after being duplicated to n.
[n]<&数字-将数字代表的fd移动到移动到n或0代表的fd。数字会在复制到n后关闭。
Similarly, the redirection operator
讯享网[n]>&digit-
moves the file descriptor digit to file descriptor n, or the standard output (file descriptor 1) if n is not specified.
[n]>&数字-将数字代表的fd移动到n代表的fd,或标准输出。
3.6.10 Opening File Descriptors for Reading and Writing 打开文件描述符同时支持读写
The redirection operator
[n]<>word
causes the file whose name is the expansion of word to be opened for both reading and writing on file descriptor n, or on file descriptor 0 if n is not specified. If the file does not exist, it is created.
[n]<>单词将单词代表的文件打开用于支持读写,n的默认值是0。
3.7 Executing Commands 执行命令
3.7.1 Simple Command Expansion 简单命令执行
When a simple command is executed, the shell performs the following expansions, assignments, and redirections, from left to right, in the following order.
在简单命令执行的时候,shell会执行如下扩展、赋值和重定向:
- The words that the parser has marked as variable assignments (those preceding the command name) and redirections are saved for later processing.
保存命令前的变量赋值和重定向后的词供以后处理。 - The words that are not variable assignments or redirections are expanded (see Shell Expansions). If any words remain after expansion, the first word is taken to be the name of the command and the remaining words are the arguments.
其它词进行执行扩展。如果展开后的第一个单词作为命令名称,其余单词作为参数。 - Redirections are performed as described above (see Redirections).
执行重定向。 - The text after the ‘=’ in each variable assignment undergoes tilde expansion, parameter expansion, command substitution, arithmetic expansion, and quote removal before being assigned to the variable.
变量赋值语句中=后面的文本在赋值给变量之前要经过一些扩展。
If no command name results, the variable assignments affect the current shell environment. Otherwise, the variables are added to the environment of the executed command and do not affect the current shell environment. If any of the assignments attempts to assign a value to a readonly variable, an error occurs, and the command exits with a non-zero status.
如果没有命令名称,变量赋值会影响当前shell环境,否则只用于要执行的命令。
If no command name results, redirections are performed, but do not affect the current shell environment. A redirection error causes the command to exit with a non-zero status.
如果没有命令名称,仍会执行重定向,但不影响当前shell环境。
If there is a command name left after expansion, execution proceeds as described below. Otherwise, the command exits. If one of the expansions contained a command substitution, the exit status of the command is the exit status of the last command substitution performed. If there were no command substitutions, the command exits with a status of zero.
如果展开后还有命令名,则以后面的步骤执行。
3.7.2 Command Search and Execution 命令搜索和执行
After a command has been split into words, if it results in a simple command and an optional list of arguments, the following actions are taken.
- If the command name contains no slashes, the shell attempts to locate it. If there exists a shell function by that name, that function is invoked as described in Shell Functions.
如果命令名称不包含/则,则shell会尝试定位它。如果存在同名的shell函数则执行。 - If the name does not match a function, the shell searches for it in the list of shell builtins. If a match is found, that builtin is invoked.
如果不是shell函数则会从shell内置命令中搜索。 - If the name is neither a shell function nor a builtin, and contains no slashes, Bash searches each element of
$PATHfor a directory containing an executable file by that name. Bash uses a hash table to remember the full pathnames of executable files to avoid multiplePATHsearches (see the description ofhashin Bourne Shell Builtins). A full search of the directories in$PATHis performed only if the command is not found in the hash table. If the search is unsuccessful, the shell searches for a defined shell function namedcommand_not_found_handle. If that function exists, it is invoked in a separate execution environment with the original command and the original command’s arguments as its arguments, and the function’s exit status becomes the exit status of that subshell. If that function is not defined, the shell prints an error message and returns an exit status of 127.
如果命令既不是shell函数也不是内置命令也不包含/,则会在$PATH寻找包含该命令的文件夹。Bash使用哈希表记录可执行文件的完整路径以避免多次PATH搜索。仅当在哈希表中找不到命令时,才会对$PATH中的目录进行完整的搜索。如果搜索不成功,shell将调用一个名为command_not_found_handle的函数。如果未定义该函数,则shell将打印错误并返回退出状态127。 - If the search is successful, or if the command name contains one or more slashes, the shell executes the named program in a separate execution environment. Argument 0 is set to the name given, and the remaining arguments to the command are set to the arguments supplied, if any.
如果搜索成功或者命令包含/,则执行指定的程序。 - If this execution fails because the file is not in executable format, and the file is not a directory, it is assumed to be a shell script and the shell executes it as described in Shell Scripts.
如果文件不是可执行格式,则假定按照shell脚本的方式执行。 - If the command was not begun asynchronously, the shell waits for the command to complete and collects its exit status.
如果命令非异步,shell会等待命令完成并收集其退出状态。
3.7.3 Command Execution Environment 命令执行环境
The shell has an execution environment, which consists of the following:
Shell的执行环境包含如下内容。
- open files inherited by the shell at invocation, as modified by redirections supplied to the
execbuiltin
打开继承或重定向的文件 - the current working directory as set by
cd,pushd, orpopd, or inherited by the shell at invocation
当前工作目录 - the file creation mode mask as set by
umaskor inherited from the shell’s parent
文件创建模式掩码 - current traps set by
trap
trap设置的信号捕获 - shell parameters that are set by variable assignment or with
setor inherited from the shell’s parent in the environment
来自变量赋值和环境中的shell参数 - shell functions defined during execution or inherited from the shell’s parent in the environment
在shell执行期间或从环境中继承的函数 - options enabled at invocation (either by default or with command-line arguments) or by
set
通过set或命令行参数设置的选项 - options enabled by
shopt(see The Shopt Builtin)
shopt设置的选项 - shell aliases defined with
alias(see Aliases)
shell别名 - various process IDs, including those of background jobs (see Lists), the value of
$$, and the value of$PPID
各种进程ID
When a simple command other than a builtin or shell function is to be executed, it is invoked in a separate execution environment that consists of the following. Unless otherwise noted, the values are inherited from the shell.
当执行函数之外的简单命令时,将在由以下内容组成的单独环境中调用:
- the shell’s open files, plus any modifications and additions specified by redirections to the command
打开继承或重定向的文件 - the current working directory
当前工作目录 - the file creation mode mask
文件创建掩码 - shell variables and functions marked for export, along with variables exported for the command, passed in the environment (see Environment)
- traps caught by the shell are reset to the values inherited from the shell’s parent, and traps ignored by the shell are ignored
A command invoked in this separate environment cannot affect the shell’s execution environment.
在单独环境中创建的命令不会影响shell执行环境。
Command substitution, commands grouped with parentheses, and asynchronous commands are invoked in a subshell environment that is a duplicate of the shell environment, except that traps caught by the shell are reset to the values that the shell inherited from its parent at invocation. Builtin commands that are invoked as part of a pipeline are also executed in a subshell environment. Changes made to the subshell environment cannot affect the shell’s execution environment.
命令替换、用括号分组的命令和异步命令在子shell环境中调用,除了shell trap的信号从父shell继承。对子shell的修改不会影响shell执行环境。
Subshells spawned to execute command substitutions inherit the value of the -e option from the parent shell. When not in POSIX mode, Bash clears the -e option in such subshells.
为执行命令替换而产生的子shell从父shell继承-e选项(set -e)的值。
If a command is followed by a ‘&’ and job control is not active, the default standard input for the command is the empty file /dev/null. Otherwise, the invoked command inherits the file descriptors of the calling shell as modified by redirections.
如果命令后跟&且作业控制未激活,则该命令的默认标准的输入是空文件,否则继承当前shell的fd,像重定向所修改的那样。
3.7.4 Environment 环境
When a program is invoked it is given an array of strings called the environment. This is a list of name-value pairs, of the form name=value.
程序被调用时,会收到一个键值对,称为环境。
Bash provides several ways to manipulate the environment. On invocation, the shell scans its own environment and creates a parameter for each name found, automatically marking it for export to child processes. Executed commands inherit the environment. The export and ‘declare -x’ commands allow parameters and functions to be added to and deleted from the environment. If the value of a parameter in the environment is modified, the new value becomes part of the environment, replacing the old. The environment inherited by any executed command consists of the shell’s initial environment, whose values may be modified in the shell, less any pairs removed by the unset and ‘export -n’ commands, plus any additions via the export and ‘declare -x’ commands.
在调用时,shell会将环境中扫描到的参数导出到子进程。export和declare -x可以在环境中增删参数和函数。环境中的参数值可以被修改。执行的命令继承的环境由shell的初始环境构成。
The environment for any simple command or function may be augmented temporarily by prefixing it with parameter assignments, as described in Shell Parameters. These assignment statements affect only the environment seen by that command.
If the -k option is set (see The Set Builtin), then all parameter assignments are placed in the environment for a command, not just those that precede the command name.
如果设置了-k选项,则所有参数的分配都会放置在命令的环境中。
When Bash invokes an external command, the variable ‘$_’ is set to the full pathname of the command and passed to that command in its environment.
$_代表命令的命令的完整路径名,可以在命令内访问,也可以在shell中访问。
3.7.5 Exit Status
The exit status of an executed command is the value returned by the waitpid system call or equivalent function. Exit statuses fall between 0 and 255, though, as explained below, the shell may use values above 125 specially. Exit statuses from shell builtins and compound commands are also limited to this range. Under certain circumstances, the shell will use special values to indicate specific failure modes.
退出状态是通过waitpid系统调用返回的值。退出状态介于0到255之间,但shell会将高于125的值视为特殊值,由自己使用。
For the shell’s purposes, a command which exits with a zero exit status has succeeded. A non-zero exit status indicates failure. This seemingly counter-intuitive scheme is used so there is one well-defined way to indicate success and a variety of ways to indicate various failure modes. When a command terminates on a fatal signal whose number is N, Bash uses the value 128+N as the exit status.
以0状态退出表示成功,非0表示失败,这是一种看似违反直觉的方案,但因失败的原因有很多,所以只分配一个数字0表示失败并不合适。当命令以编号为N的失败信号终止时,Bash使用128+N作为退出状态。
If a command is not found, the child process created to execute it returns a status of 127. If a command is found but is not executable, the return status is 126.
如果未找到命令,则为执行它而创建的子进程返回127,若找到了命令但不可执行则返回126.
If a command fails because of an error during expansion or redirection, the exit status is greater than zero.
The exit status is used by the Bash conditional commands (see Conditional Constructs) and some of the list constructs (see Lists).
退出状态用于分支结构和列表结构。
All of the Bash builtins return an exit status of zero if they succeed and a non-zero status on failure, so they may be used by the conditional and list constructs. All builtins return an exit status of 2 to indicate incorrect usage, generally invalid options or missing arguments.
所有内容功能都特殊状态2表示用法错误,通常是无效的选项或缺少参数。
3.7.6 Signals
When Bash is interactive, in the absence of any traps, it ignores SIGTERM (so that ‘kill 0’ does not kill an interactive shell), and SIGINT is caught and handled (so that the wait builtin is interruptible). When Bash receives a SIGINT, it breaks out of any executing loops. In all cases, Bash ignores SIGQUIT. If job control is in effect (see Job Control), Bash ignores SIGTTIN, SIGTTOU, and SIGTSTP.
当bash处于交互状态时,它会忽略SIGTERM(因此kill 0不会杀死交互式终端,0表示当前进程组的所有进程,默认发送的信号是15) SIGTERM,可以通过kill -l列出所有信号),SIGINT会被捕获和处理(因此内置命令wait是可中断的)。当Bash收到SIGINT时,会打断正在执行的循环。Bash会始终忽略SIGQUIT。如果作业控制生效,Bash会忽略SIGTIN、SIGTTOU和SIGTSTP。
Non-builtin commands started by Bash have signal handlers set to the values inherited by the shell from its parent. When job control is not in effect, asynchronous commands ignore SIGINT and SIGQUIT in addition to these inherited handlers. Commands run as a result of command substitution ignore the keyboard-generated job control signals SIGTTIN, SIGTTOU, and SIGTSTP.
由Bash启动的非内置命令将信号处理程序设置为shell从其父级继承的值。(是说信号会被不断向父进程传递吗?)
The shell exits by default upon receipt of a SIGHUP. Before exiting, an interactive shell resends the SIGHUP to all jobs, running or stopped. Stopped jobs are sent SIGCONT to ensure that they receive the SIGHUP. To prevent the shell from sending the SIGHUP signal to a particular job, it should be removed from the jobs table with the disown builtin (see Job Control Builtins) or marked to not receive SIGHUP using disown -h.
shell在收到挂起信号后会默认退出,在退出之前,交互式shell会将SIGHUP广播给所有正在运行或停止的作业。可以通过disown将作业从作业表中删除,以避免被广播到。
If the huponexit shell option has been set with shopt (see The Shopt Builtin), Bash sends a SIGHUP to all jobs when an interactive login shell exits.
如果已使用shopt设置了huponexit选项,则当交互式登录shell退出时,Bash会向所有作业发送SIGHUP。
If Bash is waiting for a command to complete and receives a signal for which a trap has been set, the trap will not be executed until the command completes. When Bash is waiting for an asynchronous command via the wait builtin, the reception of a signal for which a trap has been set will cause the wait builtin to return immediately with an exit status greater than 128, immediately after which the trap is executed.
如果bash在等待命令完成并接收到已设置trap的信号,则在命令完成之前不会执行trap。当Bash通过wait等待异步命令时,收到信号会立即返回,退出状态大于128,然后立即执行trap。
3.8 Shell Scripts
A shell script is a text file containing shell commands. When such a file is used as the first non-option argument when invoking Bash, and neither the -c nor -s option is supplied (see Invoking Bash), Bash reads and executes commands from the file, then exits. This mode of operation creates a non-interactive shell. The shell first searches for the file in the current directory, and looks in the directories in $PATH if not found there.
shell脚本是包含shell命令的文本文件,如果在执行bash时将此文件作为第一个参数,bash将从文件中读取和执行命令,最后退出。这种操作模式会创建一个非交互式外壳。shell首先在当前目录搜索脚本文件,如果找不到就在$PATH中搜索。
When Bash runs a shell script, it sets the special parameter 0 to the name of the file, rather than the name of the shell, and the positional parameters are set to the remaining arguments, if any are given. If no additional arguments are supplied, the positional parameters are unset.
执行shell脚本时,$0是文件名,而不是shell的名字。
A shell script may be made executable by using the chmod command to turn on the execute bit. When Bash finds such a file while searching the $PATH for a command, it spawns a subshell to execute it. In other words, executing
讯享网filename arguments
is equivalent to executing
bash filename arguments
可以通过chmod命令为shell脚本授予执行权限。当bash在$PATH中找到这样的文件时,会生成一个子shell来执行它。如果文件名可执行,执行文件名 参数等价于bash 文件名 参数。子shell重新初始化自己,效果上就像调用了一个新的shell来解释脚本。
if filename is an executable shell script. This subshell reinitializes itself, so that the effect is as if a new shell had been invoked to interpret the script, with the exception that the locations of commands remembered by the parent (see the description of hash in Bourne Shell Builtins) are retained by the child.
Most versions of Unix make this a part of the operating system’s command execution mechanism. If the first line of a script begins with the two characters ‘#!’, the remainder of the line specifies an interpreter for the program and, depending on the operating system, one or more optional arguments for that interpreter. Thus, you can specify Bash, awk, Perl, or some other interpreter and write the rest of the script file in that language.
如果脚本的每一行以#!开头,则可以指定程序的解释器,并且可以为解释器指定可选参数。
The arguments to the interpreter consist of one or more optional arguments following the interpreter name on the first line of the script file, followed by the name of the script file, followed by the rest of the arguments supplied to the script. The details of how the interpreter line is split into an interpreter name and a set of arguments vary across systems. Bash will perform this action on operating systems that do not handle it themselves. Note that some older versions of Unix limit the interpreter name and a single argument to a maximum of 32 characters, so it’s not portable to assume that using more than one argument will work.
在脚本每一行的解释器名称的后面是参数,然后是脚本名称,最后是其余参数。该行如何拆分为解释器名称和参数的细节因系统而异。
Bash scripts often begin with #! /bin/bash (assuming that Bash has been installed in /bin), since this ensures that Bash will be used to interpret the script, even if it is executed under another shell. It’s a common idiom to use env to find bash even if it’s been installed in another directory: #!/usr/bin/env bash will find the first occurrence of bash in $PATH.
#!称为Sharp bang,简称shebang。#!后面通常是/bin/bash表示解释器路径,还有常见是的/usr/bin/env bash,env可以从$PATH中找到bash的位置并执行。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/98425.html