Skip to content

Bash arrays API

Bash 测试表达式 —— 用于 [ ] 和 [[ ]] 条件判断中的文件、字符串和数值比较。

1 class · 7 methods

测试/条件

7 methods

用于 [ (test) 命令和更强大的 [[ ]] 复合命令的测试运算符。

arr=(a b c)

如果 file 存在且是常规文件(不是目录或设备),则返回 true。

Returns

array

Example

bash
fruits=("apple" "banana" "cherry")
echo ${fruits[1]}  # banana

# Append on declaration
nums=(1 2 3 4 5)
${arr[index]}

如果 dir 存在且是目录,则返回 true。

Parameters

NameTypeDescription
dirinteger要测试的路径。

Returns

string

Example

bash
arr=("a" "b" "c")
echo ${arr[0]}  # a
echo ${arr[2]}  # c
arr[5]="z"       # sparse: index 3,4 are empty
${arr[@]}

如果 string 的长度为零(空),则返回 true。

Returns

string list

Example

bash
arr=("a" "b" "c")
echo ${arr[@]}   # a b c
for x in "${arr[@]}"; do
    echo "x=$x"
done
${#arr[@]}

如果 string 的长度不为零(非空),则返回 true。

Returns

integer

Example

bash
arr=("a" "b" "c")
echo ${#arr[@]}  # 3

arr[10]="z"
echo ${#arr[@]}  # 4 (sparse array)
arr+=(d e)

如果两个字符串相等,则返回 true。使用 != 判断不等。

Parameters

NameTypeDescription
str1string第一个字符串。

Returns

array

Example

bash
arr=("a" "b")
arr+=("c" "d")
echo ${arr[@]}  # a b c d
unset arr[index]

如果两个整数相等,则返回 true。其他数值运算:-ne、-lt、-le、-gt、-ge。

Parameters

NameTypeDescription
num1integer第一个整数。

Returns

void

Example

bash
arr=("a" "b" "c")
unset arr[1]
echo ${arr[@]}    # a c
echo ${arr[1]}    # (empty)
${arr[@]:start:count}

如果 path 存在(任何类型:文件、目录、符号链接等),则返回 true。

Parameters

NameTypeDescription
pathinteger要测试的路径。
countintegerNumber of elements.

Returns

string list

Example

bash
arr=(1 2 3 4 5)
echo ${arr[@]:1:3}  # 2 3 4
echo ${arr[@]:2}    # 3 4 5 (to end)