Shell数组
2015-12-08 12:32
591 查看
1.Shell数组的定义
1.1空数组定义
#define a null array null_arr=() null_arr[0]=test null_arr[1]=2 echo ${null_arr[1]} $null_arr #2 test
注意:
如果直接打印数组名$null_arr,那么只会输出数组的第一个元素,
数组元素的数据类型可以不同。
1.2非空数组定义
#define a array with 5 elements arr=(1 2 3 4 5)
注意:数组元素是以“ ”(空格符)隔开,而不是“,”(逗号)。
2.数组的长度
#calculate the length of the array len=${#arr[@]} echo "Length of array: $len" #Length of array: 5
3.数组的遍历
3.1用像C语言中的for遍历
不过,用这种方式需要计算数组的长度。#traverse the array with C-for for ((i = 0; i < len; i++));do { echo $i"th element: ${arr[i]}" } done #0th element: 1 #1th element: 2 #2th element: 3 #3th element: 4 #4th element: 5
3.2用下标索引遍历
#traverse the array with its index for i in "${!arr[@]}";do { echo $i"th element: ${arr[i]}" } done #0th element: 1 #1th element: 2 #2th element: 3 #3th element: 4 #4th element: 5
3.3直接访问元素
#traverse the array with for for val in ${arr[@]};do { echo $val } done #1 #2 #3 #4 #5
3.4while-do遍历
#traverse the array with while i=0 while [ $i -lt ${#arr[@]} ];do { echo $i"th element: ${arr[i]}" #i=$(($i + 1)) #let ++i let i++ } done #0th element: 1 #1th element: 2 #2th element: 3 #3th element: 4 #4th element: 5
如果只是打印数组的话,可以用下面的快捷方式,注意${arr[*]}和${arr[@]}是等价的。
echo "My array: ${arr[*]}" echo "My array: ${arr[@]}"
4.shell数组的特色
shell数组的特色
shell数组可以给任何位置赋值,而未被赋值的位置是空(没有任何元素,包括空格等)。
shell数组的长度不受定义时的长度限制。
shell数组的长度指的是数组中元素的个数。并且对第一条仍然适用,即空位置不算长度。
shell数组中元素类型可以不同。
arr[10]=test echo "current length of the array: ${#arr[@]}" echo "8th and 9th elements of the array are: ${arr[8]}, ${arr[9]}" echo "10th element of the array: ${arr[10]}" #current length of the array: 6 #8th and 9th elements of the array are: , #10th element of the array: test
完整代码:
#!/usr/bin/env bash
#define a null array
null_arr=()
null_arr[0]=test
null_arr[1]=2
echo ${null_arr[1]} $null_arr
#define a array with 5 elements arr=(1 2 3 4 5)
#calculate the length of the array
len=${#arr[@]}
echo "Length of array: $len"
#traverse the array with C-for
for ((i = 0; i < len; i++));do
{
echo $i"th element: ${arr[i]}"
}
done
#traverse the array with its index
for i in "${!arr[@]}";do
{
echo $i"th element: ${arr[i]}"
}
done
#traverse the array with for
for val in ${arr[@]};do
{
echo $val
}
done
#traverse the array with while
i=0
while [ $i -lt ${#arr[@]} ];do
{
echo $i"th element: ${arr[i]}"
#i=$(($i + 1))
#let ++i
let i++
}
done
arr[10]=test
echo "current length of the array: ${#arr[@]}"
echo "8th and 9th elements of the array are: ${arr[8]}, ${arr[9]}"
echo "10th element of the array: ${arr[10]}"
相关文章推荐
- Linux socket 初步
- android wifi 无线调试
- linux lsof详解
- linux 文件权限
- Linux 执行数学运算
- 10 篇对初学者和专家都有用的 Linux 命令教程
- Linux 与 Windows 对UNICODE 的处理方式
- Ubuntu12.04下QQ完美走起啊!走起啊!有木有啊!
- 解決Linux下Android开发真机调试设备不被识别问题
- 运维入门
- 运维提升
- Linux 自检和 SystemTap
- 动态清空 nohup 输出文件
- install scrapy with pip and easy_install
- Ubuntu Linux使用体验
- c语言实现hashmap(转载)
- Linux 信号signal处理机制
- linux下mysql添加用户