shell数组 | Linux中国

来源:百度文库 编辑:神马文学网 时间:2024/04/28 16:47:03
shell数组
Bash中还可以使用数组变量,其赋值有两种:
(1) name = (value1 ... valuen) 此时下标从0开始
(2) name[index] = value
数组下标的范围没有任何限制,同时也不必使用连续的分量.
$ A=(a b c def)
==================================================
$ echo ${A[@]} //取全部元素   比如echo ${A[0]}输出第一个元素
a b c def
//取得数组元素的个数
$ echo ${#A[@]}
4
$ A[3]=yaoshuyin //将第三个元素重新赋值
$ echo ${A[@]}
a b c yaoshuyin
==================================================
//清除变量
$ unset A
$ echo ${A[@]}
$
==================================================
//清空变量,即将值变为空
$ A=
$ echo ${A[@]}
$
==================================================
=======================示例 while循环========================
#建立数组
arrSource=("arrJobs.php" "arrSubHangye.php" "arrFirst.php" )
arrDest=("buildhr" \
"buildtrain/htdocs" \
"bankhr" \
"healthr" \
"elehr" \
)
#取数组无元素个数
lenArrSource=${#arrSource }
lenArrDest=${#arrDest }
#循环列出数组元素
i=0
while [ $i -lt $lenArrSource ]
do
echo ${arrSource[$i]}
let i++
done
i=0
while [ $i -lt $lenArrDest ]
do
echo ${arrDest[$i]}
let i++
done
=======================示例: for循环===============================
#源文件
arrSource=("/home/800hr/htdocs/login_jump.php")
#目标网站
arrDest=(ithr elehr buildhr bankhr healthr ctvhr chenhr mechr clothr cneduhr 56hr tourhr foodhr greenhr cnlawhr waimaohr)
for outer in ${arrSource } #${arrSource } 是数组中的所有元素
do
for inner in ${arrDest}
do
echo "ln -s $outer /home/${inner}/campus/"
done
done