目录
一、数组定义
数组中可以存放多个值。Bash Shell 只支持一维数组(不支持多维数组),初始化时不需要定义数组大小,与大部分编程语言类似,数组元素的下标由0开始。
Shell 数组用括号来表示,元素用"空格"符号分割开。
array_name=(value1 ... valuen)
- 定义方法
#!bin/sh
# 一次赋多个值可以这样定义
array=( one two three )
echo ${array[@]}
# 也可以这样定义
array=(
one
two
three
)
echo ${array[@]}
# 还可以单独定义数组的各个部分
array[0]=one
array[1]=two
array[2]=three
echo ${array[@]}
二、数组操作
1、获取数组长度
- 取得数组元素的个数 :${#数组名[@]}或者${#数组名[*]}
[root@localhost text]# array=(one two three)
[root@localhost text]# echo ${#array[@]}
3
[root@localhost text]# echo ${#array[*]}
3
- 取得数组单个元素的长度:${#数组名[下标]}
[root@localhost text]# echo ${#array[0]}
3
[root@localhost text]# echo ${#array[1]}
3
[root@localhost text]# echo ${#array[2]}
5
- 获取数组下标 ${!数组名[下标]}
[root@localhost text]# echo ${!array[*]}
0 1 2
2、引用数组
- 获取单个元素${数组名[下标]}
[root@localhost text]# echo ${array[1]}
two
[root@localhost text]# echo ${array[0]}
one
[root@localhost text]# echo ${array[2]}
three
- 获取全部元素 ${数组名[@]}或者${数组名[*]}
[root@localhost text]# echo ${array[@]}
one two three
[root@localhost text]# echo ${array[*]}
one two three
3、遍历数组
- 通过数组下标来遍历数组:
array=( one two three )
for i in ${!array[@]}
do
echo ${array[i]}
done
执行结果 :
one
two
three
- 直接遍历数组
array=( one two three )
for i in ${array[@]}
do
echo $i
done
4、数组的删除
unset array[1] # 删除数组中第一个元素
unset array # 删除整个数组
三、实际应用
1、从“标准输入”读入n次字符串,每次输入的字符串保存在数组array里
n=0
while true
do
read -p ">>>:" num
array[$n]=$num
echo ${array[@]}
let n++
done
执行结果
[root@localhost text]# vim exp_48.sh
[root@localhost text]# sh exp_48.sh
>>>:123
123
>>>:456
123 456
>>>:ss
123 456 ss
2、将字符串里的字母逐个放入数组,并输出到“标准输出”
str="abcdefgdnklsfnksjfbkjrsgsjekdflsekg"
n=0
while ((n<${#str}))
do
#echo ${str:$n:1}
array[$n]=${str:$n:1}
#echo ${array[@]}
let n++
done
echo ${array[@]}
执行结果
[root@localhost text]# sh exp_49.sh
a b c d e f g d n k l s f n k s j f b k j r s g s j e k d f l s e k g
3、把1-3 3个数字存到数组里 分别乘以8 然后依次输出。
#!/bin/bash
array1=(`seq 3`)
for ((i=0;i<${#array1[@]};i++))
do
echo $[${array1[$i]}*8]
done
[root@localhost text]# sh text01.sh
8
16
24