在 Shell 脚本代码中,命令行参数分配给变量,如下所示。语句中的逗号(,)是什么意思。在读取 Bash 脚本中的命令行参数时添加两次逗号会有什么区别。
#!/bin/bash
var1=${1,,}
var2=${2,,}
./script.sh value1 value2
答案1
它是参数扩展被称为案例修改(看man bash
)。
$var1
将包含第一个参数,所有字符都转换为小写。 Single,
只会更改参数的第一个字符。
您可以为逗号后的每个字符指定一个模式,例如以下仅小写元音:
x=$(echo {A..Z})
echo ${x,,[AEIOU]}
输出:
a B C D e F G H i J K L M N o P Q R S T u V W X Y Z
对称地,您可以使用^
转换为大写。
答案2
man bash | grep -B1 -A10 ,,
${parameter,pattern}
${parameter,,pattern}
Case modification. This expansion modifies the case of alpha‐
betic characters in parameter. The pattern is expanded to pro‐
duce a pattern just as in pathname 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 upper‐
case; the , operator converts matching uppercase letters to low‐
ercase. 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 sub‐
scripted with @ or *, the case modification operation is applied
to each member of the array in turn, and the expansion is the
resultant list.