shell數組shell
定義數組數組
[root@localhost test]# a=(1 2 3)bash
輸出整個數組dom
[root@localhost test]# echo ${a[@]}ide
1 2 3排序
輸出指定數組元素it
[root@localhost test]# echo ${a[0]}class
1test
[root@localhost test]# echo ${a[1]}隨機數
2
[root@localhost test]# echo ${a[2]}
3
臨時增長數組元素
[root@localhost test]# a[4]=9
[root@localhost test]# echo ${a[@]}
1 2 3 9
修改數組元素
[root@localhost test]# a[1]=11
[root@localhost test]# echo ${a[@]}
1 11 3 9
獲取數組元素個數
[root@localhost test]# echo ${#a[@]}
4
刪除指定數組元素的值
[root@localhost test]# a=(1 11 3 9)
[root@localhost test]# echo ${a[@]}
1 11 3 9
[root@localhost test]# unset a[0]
[root@localhost test]# echo ${a[@]}
11 3 9
輸出指定長度數組元素,下例爲從第2個元素(a[0]爲第1個元素,a[1]爲第2個元素)開始,取3個元素
[root@localhost test]# a=(1 11 3 9)
[root@localhost test]# echo ${a[@]}
1 11 3 9
[root@localhost test]# echo ${a[@]:1:3}
11 3 9
用法1、獲取10個隨機數
[root@localhost test]# cat random
#!/bin/bash
for i in `seq 0 9`
do
a[$i]=$RANDOM
done
echo ${a[@]}
用法2、獲取10個隨機數並排序
[root@localhost test]# cat random
#!/bin/bash
for i in `seq 0 9`
do
a[$i]=$RANDOM
done
echo ${a[@]} | sed 's/ /\n/g' | sort -n