数组
8 methodsBash 索引数组操作:声明、访问、迭代和切片。
${#var}通过赋值一个用括号括起来的值列表来声明索引数组。
Returns
integer
Example
bash
var="Hello, World"
echo ${#var} # 12
empty=""
echo ${#empty} # 0${var:offset:length}返回给定整数索引(从 0 开始)处的元素。
Parameters
| Name | Type | Description |
|---|---|---|
| index | integer | 从 0 开始的索引。 |
| length | integer | Number of characters (optional). |
Returns
string
Example
bash
var="Hello, World"
echo ${var:0:5} # Hello
echo ${var:7} # World
echo ${var: -5} # World (note space before -)${var/old/new}展开为数组的所有元 素,作为独立的带引号单词。使用 [*] 可作为单个单词。
Parameters
| Name | Type | Description |
|---|---|---|
| old | pattern | Glob pattern to match. |
| new | string | Replacement string. |
Returns
string
Example
bash
var="a-b-c"
echo ${var/-/_} # a_b-c (only first)${var//old/new}返回数组中已赋值元素的数量(不是最高索引)。
Parameters
| Name | Type | Description |
|---|---|---|
| old | pattern | Glob pattern to match. |
| new | string | Replacement string. |
Returns
string
Example
bash
var="a-b-c"
echo ${var//-/_} # a_b_c (all matches)
path="/usr/local/bin"
echo ${path//\//_} # _usr_local_bin (escape / in pattern)${var#prefix}将一个或多个元素追加到现有索引数组的末尾。
Parameters
| Name | Type | Description |
|---|---|---|
| elements | pattern | 要追加的值。 |
Returns
string
Example
bash
path="/usr/local/bin"
echo ${path#/usr} # /local/bin
file="archive.tar.gz"
echo ${file#*.} # tar.gz (shortest)${var%suffix}移除给定索引处的元素。数组变为稀疏的;索引不会移动。
Parameters
| Name | Type | Description |
|---|---|---|
| index | pattern | 要移除元素的索引。 |
Returns
string
Example
bash
file="archive.tar.gz"
echo ${file%.gz} # archive.tar
echo ${file%.*} # archive.tar (shortest from end)
echo ${file%%.*} # archive (longest from end)${var^^}返回从索引 start 开始的 count 个元素的切片。
Returns
string
Example
bash
var="Hello, World"
echo ${var^^} # HELLO, WORLD${var,,}Returns the value of var converted to lowercase. Requires Bash 4.0+.
Returns
string
Example
bash
var="Hello, World"
echo ${var,,} # hello, world