什么是shell数组
数组就是把n个变量或者字符内容集合起来用一个名字命名
接着用编号对它们区分的元素集合,这个名字叫数组名
区分不同内容的是编号,叫数组下标
有了数组,就能用一样的名字引用不同的变量或者变量值,并通过数字来识别它们
使用数组也能使代码缩短简洁等好处
应用场景包括
1,获取数组长度
2.获取元素长度
3,遍历元素
4,元素切片
5,元素替换
6 ,元素删除
**那么到底什么是数组呢?
就是相同类型数据的结合
在内存中开辟了连续的空间,列如(11;22;33 )
**
数组的定义方法
这里数组的定义方法大概有四种
方法一:
方法二
方法三
方法四
实例
读取数组
读取数组元素的一般格式:
${array_name[index]}
示例:
#!/bin/bash
array=( one two three )
echo “第一个元素为: ${array[0]}”
echo “第二个元素为: ${array[1]}”
echo "第三个元素为: ${array[2]}"
执行脚本的结果:
** 第一个元素为: one
第二个元素为: two
第三个元素为: three**
2、获取数组中的所有元素
使用 @ 或 * 可以获取数组中的所有元素
array=( one two three )
echo ${array[@]}
echo ${array[*]}
执行后,结果:
one two three
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 ${array[i]}
done
执行后结果:
one
two
three