(Turn) shell variables and expansion

1. shell variables

The shell variable assignment statement is "name=[value]", and there can be no spaces on both sides of the equal sign. You can append the content "name+=value" to the shell variable, and use "unset name" to cancel the setting of the shell variable. The example is as follows.

$ var=1
$ echo $var
1 $ var=123 $ echo $var 123 $ var+=100 $ echo $var 123100 $ var=a $ echo $var a $ var=abc $ echo $var abc $ var+=xxx $ echo $var abcxxx $ unset var $ echo $var

2, shell expansion

After the command line is split into symbols, it needs to be expanded. There are many ways to expand, and there is a certain order: brace expansion, tilde expansion, parameter, variable and arithmetic expansion and command substitution (from left to right), word splitting , and filename expansion, and if the system supports it, there is another expansion, process substitution, which goes hand in hand with parameter, variable, and arithmetic expansion, and command substitution. Only brace expansion, word expansion, and filename expansion can change the number of words when expanding. Other expansions are single-word expansion into a single-word, with the only exception being the expansion of "$@"sums "${array[@]}", which are removed after all expansions are completed. These shell extensions are introduced one by one below.

3. Braces expansion

Braces expansion is a mechanism that can generate arbitrary strings, in the basic form "prefix{var,var2,var3…}suffix" or "prefix{x..y[..increment]}suffix". The prefix prefix and suffix suffix of brace expansion are optional, and the content in braces is a comma-separated string or a sequence expression, which is expanded from left to right. For strings, they are separated by commas. If there is only one string, the effect of whether there is a comma after the string is different. For sequence expressions, x and y are an integer or a single character, the type must be the same, and the following increment is an optional integer value, the default is 1 or -1, which is selected according to the size of x and y, when When x and y are integers, a 0 can be added in front of the integer to limit the width of the integer. When the high-order bit is insufficient, it is filled with 0, and finally expanded to include a value between the smaller value and the larger value of x and y. Series value.

$ foo() { echo a{foo, bar}z; }
$ foo
afooz abarz
$ foo() { echo a{01..10..2}z; } $ foo a01z a03z a05z a07z a09z

A well-formed brace expansion must contain unquoted opening and closing braces, and at least one unquoted comma or sequence expression. Braces expansion occurs before all other expansions. To avoid conflicts with parameter expansion, brace expansion does not recognize "${" in strings. To prevent being considered part of brace expansion, braces and commas can be reversed using Slash escape.

4. Tilde extension

If a word begins with an unquoted tilde "~", all characters following it, up to the first unquoted slash (if any), are treated as tilde prefixes. If none of the characters in the tilde prefix are quoted, all characters after the tilde are treated as a possible login username. If the login name is an empty string, the tilde is replaced with a special shell variable The value of HOME, if HOME is not set, is replaced with the home directory of the user who executed the command, otherwise, replaced with the home directory of the specified login name.

~    扩展为"$HOME"
~/foo    扩展为"$HOME/foo"
~username/foo    扩展为用户username的主目录中的子目录foo

In the tilde prefix, there can be plus and minus signs.

~+    扩展为"$PWD"
~-    扩展为"$OLDPWD"

In the tilde prefix, you can also use integers to expand the directory stack (the corresponding built-in commands are pushd, popd, dirs).

~N    命令"dirs +N"显示的字符串
~+N    命令"dirs +N"显示的字符串
~-N 命令"dirs -N"显示的字符串

5. Parameter (variable) expansion

Parameter expansion is guided by the dollar sign "$", and the parameters are generally placed in a pair of unquoted braces. The basic format is:

${parameter}

 

Several situations where the colon ":" is used:

${parameter:-word}    如果parameter没有设置或者为空,替换为word;否则替换为parameter的值。 ${parameter:+word} 如果parameter没有设置或者为空,不进行任何替换;否则替换为word。 ${parameter:=word} 如果parameter没有设置或者为空,把word赋值给parameter。最终替换为parameter的值。 ${parameter:?word} 如果parameter没有设置或者为空,把word输出到stderr,否则替换为parameter的值。 ${parameter:offset} 扩展为parameter中从offset开始的子字符串。 ${parameter:offset:length} 扩展为parameter中从offset开始的长度不超过length的字符。

Several situations where the exclamation mark "!" is used (indirect expansion):

${!prefix*}    扩展为变量名中含有prefix的一些变量。
${!prefix@}    扩展为变量名中含有prefix的一些变量。
${!name[*]}    如果name为数组,扩展为name的索引;否则结果为0。如果name未定义,结果为空。 ${!name[@]} 如果name为数组,扩展为name的索引;否则结果为0。如果name未定义,结果为空。

 

Several situations where the pound sign "#" is used:

${#parameter}    结果为parameter所包含的字符数。
${parameter#word}    word与parameter从最左边开始进行模式匹配,结果为从parameter最左边删除匹配到的最短字符串后剩下的内容。
${parameter##word} word与parameter从最左边开始进行模式匹配,结果为从parameter最左边删除匹配到的最长字符串后剩下的内容。

 

Several situations where the percent sign "%" is used (as opposed to "#"):

${parameter%word}    word与parameter从最右边开始进行模式匹配,结果为从parameter最右边删除匹配到的最短字符串后剩下的内容。
${parameter%%word}     word与parameter从最右边开始进行模式匹配,结果为从parameter最右边删除匹配到的最长字符串后剩下的内容。

String replacement:

${parameter/pattern/string}    pattern为一种模式,把parameter中与之匹配的最长字符串用string替换。若pattern以#开头,只匹配parameter的开头;若pattern以%开头,只匹配parameter的结尾;若pattern以/开头,会替换所有匹配到的内容,否则只替换第一个匹配到的内容;若string为空,可省略pattern后面的/,表示删除匹配到的内容。

 

Character case conversion (when pattern is omitted, it means that each character can be matched?):

${parameter^pattern}    把parameter中与pattern匹配的第一个字符转为大写字母。
${parameter^^pattern}    把parameter中与pattern匹配的所有字符转为大写字母。
${parameter,pattern}    把parameter中与pattern匹配的第一个字符转为小写字母。
${parameter,,pattern}    把parameter中与pattern匹配的所有字符转为小写字母。

 

6. Arithmetic expansion

Arithmetic expansion can do a real math operation in the form:

$((expression))

 

E.g:

$ foo=1
$ var=$((foo+=10)) $ echo $var 11

 

7. Command substitution

Command substitution replaces the standard output of the command execution with the command itself, in the format:

$(command)
`command`

 

E.g:

$ uname -p
x86_64
$ foo=$(uname -p)
$ echo $foo x86_64

 

8. Process replacement

If the system supports named pipes "fifo" or can name open files as "/dev/fd", then process substitution is also supported. The format is:

<(command)
>(command)

 

There must be no space between the angle brackets and the left parenthesis in process substitution. When a command is executed, its input and output are associated with a named pipe fifo or a file in the /dev/fd directory, as if the input and output of the command are tied to the input and output streams of another process. 
E.g:

$ echo "hello" > test.sh
$ echo "world" >> test.sh
$ cat test.sh hello world $ grep hello <(cat test.sh) hello $ echo aa bb cc dd >(awk '{print $1}') aa bb cc dd /dev/fd/63 $ echo aa bb cc dd > /dev/fd/63 >(awk '{print $1}') $ aa $ echo aa bb cc dd > /dev/fd/63 >(awk '{print $2}') $ bb $ echo aa bb cc dd > /dev/fd/63 >(awk '{print $3}') $ cc $ echo aa bb cc dd > /dev/fd/63 >(awk '{print $4}') $ dd

9. Word split

Word splitting occurs in shell expansion. The related system variable is IFS, that is, Internal Field Separator. The default value is <space><tab><newline>. These delimiters appear at the beginning or end of the line of the shell expansion result and will be ignored. In other places, they are used as delimiters. words are separated.

10. File name extension

After the word is split, Bash will search for "*", "?", "[" in each word, and if one of them is found, it will perform pattern matching. The built-in command shopt is related to pattern matching. The following describes the patterns in pattern matching. Several special symbols.

*    匹配任何字符串,包括空字符串。
?    匹配任意单个字符。
[...]    匹配方括号中的任一字符。可以是一个范围表达式,由连字符连接一对字符,这个范围受当前语言环境的影响。如果方括号后面的第一个字符是“!”或“^”,则匹配任一没有出现在方括号中的字符。如果要匹配字符“-”,可以把它放在方括号中的第一个或最后一个位置,如果要匹配字符“]”,可以把它放在方括号中的第一个位置。
[[:class:]]    通过class指定字符类别,class可以是POSIX标准中的下列关键字:alnum、alpha、ascii、blank、cntrl、digit、graph、lower、print、punct、space、upper、word、xdigit,其中word表示大小写字母、数字和下划线。
[[=c=]]    匹配所有的字符c。
[[.symbol.]]    匹配所有的符号symbol。
?(pattern-list)    匹配pattern-list零次或一次。
*(pattern-list)    匹配pattern-list零次或多次。
+(pattern-list)    匹配pattern-list一次或多次。
@(pattern-list)    匹配pattern-list中的某个模式。
!(pattern-list)    与pattern-list中的所有模式都不匹配的其它情形。

 

11. Reference deletion

After the shell expansion mentioned above, for all unquoted characters, including backslash "\", single quote "'" and double quote """, if not generated by shell expansion, it will be deleted, Ultimately yields real results.

Copyright statement: This article is an original article by the blogger and may not be reproduced without the blogger's permission. https://blog.csdn.net/iEearth/article/details/52548525

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325818526&siteId=291194637