數組是一個很有用的數據結構,經常使用的功能有初始化,遍歷,查找,獲取數組長度等操作
一、初始化
小括號中使用空格分開的數據結構就是一個數組,也可使用下標添加元素
arr=(1 'nice' '2days')
arr[3]='yum'
二、輸出數組
echo ${arr[*]} ## *也可以使用@代替
三、遍歷數組
for e in ${arr[*]};do echo $e done
四、獲取指定索引元素
echo ${arr[1]}
五、獲取數組長度
echo ${#arr[*]}
實際應用
1、將/usr/local下的數據放入數組
arr=`ls /usr/local` ### 也可寫成:arr=$(ls /usr/local) for e in ${arr[*]};do echo $e done
2、將文件中的內容放入數組
file文件內容如下
apple,pen,orange
讀取文件,通過管道,將逗號變為空格,就形成了一個數組,源文件內容不會變動
for e in `cat ./file | sed 's/,/ /g'`;do echo $e done
3、找出/usr/local下文件所有者和所在組均為tomcat的文件夾
for e in `ls -l /usr/local | awk '{print $3 $4":" $9}'`;do if [ "`echo $e | cut -d ':' -f 1`" == "tomcattomcat" ];then echo "`echo $e | cut -d ':' -f 2`" fi done