標籤:shell linux
1.數組的介紹
平時定義a=1;b=2;c=3,變數多了,再一個一個定義就費勁了。
簡單的說數組就是資料類型的元素按一定順序排列的集合。
數組就是有限個元素變數或資料用一個名字命名,然後用編號區分他們的變數的集合,這個名字稱為數組,編號稱為數組的下標。組成數組的多個變數稱為數組的分量,也稱為數組的元素,有時也稱為下標變數。
2.數組的定義與增刪改查
(1) 數組的定義
一對括弧表示數組,數組元素用“空格”符號分隔開
array=(value1 value2 value3….)
[[email protected] ~]# array=(1 2 3)
(2) 擷取數組的長度
[[email protected] ~]# echo ${#array[*]}3[[email protected] ~]# echo ${#array[@]}3
(3) 列印數組元素
[[email protected] ~]# echo ${array[0]}1[[email protected] ~]# echo ${array[1]}2[[email protected] ~]# echo ${array[2]}3[[email protected] ~]# echo ${array[*]}1 2 3
(4) for迴圈列印數組
方法一:
[[email protected] jiaobenlianxi]# cat array01.sh array=( 192.168.1.111 192.168.1.112 192.168.1.113)for ip in ${array[*]}do echo $ip sleep 2done[[email protected] jiaobenlianxi]# sh array01.sh 192.168.1.111192.168.1.112192.168.1.113
方法二:用C語言方式
[[email protected] jiaobenlianxi]# cat array02.sh array=( 192.168.1.114 192.168.1.115 192.168.1.116)for((i=0;i<${#array[*]};i++))do echo ${array[i]} sleep 2done[[email protected] jiaobenlianxi]# sh array02.sh 192.168.1.114192.168.1.115192.168.1.116
(5) 數組的增加
[[email protected] jiaobenlianxi]# array=(1 2 3)[[email protected] jiaobenlianxi]# echo ${array[*]}1 2 3[[email protected] jiaobenlianxi]# array[3]=4[[email protected] jiaobenlianxi]# echo ${array[*]}1 2 3 4
(6) 刪除數組
[[email protected] jiaobenlianxi]# unset array[0][[email protected] jiaobenlianxi]# echo ${array[*]}2 3 4
(7) 數組內容的截取和替換(和變數子串的替換很像)
截取:
[[email protected] jiaobenlianxi]# array=(1 2 3 4 5)[[email protected] jiaobenlianxi]# echo ${array[*]:1:3}2 3 4[[email protected] jiaobenlianxi]# echo ${array[*]:3:4}4 5
替換:
[[email protected] jiaobenlianxi]# echo ${array[*]/3/4} 把數組中的3替換成4臨時替換,原數組未做改變1 2 4 4 5[[email protected] jiaobenlianxi]# array1=(${array[*]/3/4})[[email protected] jiaobenlianxi]# echo ${array1[*]}1 2 4 4 5
3.命令結果定義數組
[[email protected] jiaobenlianxi]# array=($(ls))[[email protected] jiaobenlianxi]# echo ${array[1]}1.sh[[email protected] jiaobenlianxi]# echo ${array[2]}a.log[[email protected] jiaobenlianxi]# echo ${array[3]}array01.sh[[email protected] jiaobenlianxi]# echo ${array[*]}1-100.sh 1.sh a.log array01.sh array02.sh beijingcolor.sh b.log break.sh case01.sh check.sh chkconfigoff.sh chkconfigon.sh color1.sh color.sh for1-1000.sh for1-100_3.sh for1-100.sh for1.sh for2.sh for3.sh for4.sh for5.sh hanshu01.sh hanshu02.sh huafei.sh menufruit.sh nginx.sh piliangxiugai1.sh piliangxiugai2.sh piliangxiugai3.sh suijiwnjian.sh sum1-100.sh test uptime.sh usage.sh user.sh while1.sh while2.sh while3.sh while4.sh while.sh zhuajiu.sh[[email protected] jiaobenlianxi]# cat array03.sharray=( $(ls))for((i=0;i<${#array[*]};i++))do echo ${array[i]}done
4.Shell數組知識小結
(1)定義:
靜態數組:array=(1 2 3) 空格隔開
動態數組:array=($(ls))
給數組賦值:array[3]=4
(2)列印
列印所有元素:${array[*]}或${array[@]}
列印數組長度:${#array[@]}或${#array[*]}
列印單個元素:${array[i]} i是數組下標
shell指令碼編程學習筆記-shell數組