linux-tutorial/codes/shell/demos/array-demo.sh

56 lines
854 B
Bash
Raw Normal View History

2019-02-28 19:33:08 +08:00
#!/usr/bin/env bash
# 创建数组
2019-10-10 08:56:31 +08:00
nums=( [ 2 ] = 2 [ 0 ] = 0 [ 1 ] = 1 )
colors=( red yellow "dark blue" )
2019-02-28 19:33:08 +08:00
# 访问数组的单个元素
echo ${nums[1]}
# Output: 1
# 访问数组的所有元素
echo ${colors[*]}
# Output: red yellow dark blue
echo ${colors[@]}
# Output: red yellow dark blue
printf "+ %s\n" ${colors[*]}
# Output:
# + red
# + yellow
# + dark
# + blue
printf "+ %s\n" "${colors[*]}"
# Output:
# + red yellow dark blue
printf "+ %s\n" "${colors[@]}"
# Output:
# + red
# + yellow
# + dark blue
# 访问数组的部分元素
echo ${nums[@]:0:2}
# Output:
# 0 1
# 访问数组长度
echo ${#nums[*]}
# Output:
# 3
# 向数组中添加元素
2019-10-10 08:56:31 +08:00
colors=( white "${colors[@]}" green black )
2019-02-28 19:33:08 +08:00
echo ${colors[@]}
# Output:
# white red yellow dark blue green black
# 从数组中删除元素
2019-10-10 08:56:31 +08:00
unset nums[ 0 ]
2019-02-28 19:33:08 +08:00
echo ${nums[@]}
# Output:
# 1 2