shell脚本中数组的使用

1.数组的基本用法

引用数组的形式:${arry[x]}

#!/bin/bash 

city=(nanjing beijing jinan zibo linyi)

echo "city[0]=${city[0]}"
echo "city[1]=${city[1]}"
echo "city[2]=${city[2]}"
echo "city[3]=${city[3]}"
echo "city[4]=${city[4]}"
echo "city[5]=${city[5]}"
 ~                                                                                                                                                                       
~                                                                                                                                                                       
~                                                                                                                                                                       
~                                                                                                                                                                       
运行结果:~    
[root@nn shell]# chmod +x arry1.sh 
[root@nn shell]# ./arry1.sh 
city[0]=nanjing
city[1]=beijing
city[2]=jinan
city[3]=zibo
city[4]=linyi
city[5]=

#!/bin/bash 

city=(nanjing [3]=beijing jinan zibo linyi)   //()可以给任意一个元素随机赋值

echo "city[0]=${city[0]}"
echo "city[1]=${city[1]}"
echo "city[2]=${city[2]}"
echo "city[3]=${city[3]}"
echo "city[4]=${city[4]}"
echo "city[5]=${city[5]}"
~
运行结果:                                                                                                                                                                       
~[root@nn shell]# ./arry1.sh 
city[0]=nanjing
city[1]=
city[2]=
city[3]=beijing
city[4]=jinan
city[5]=zibo

              

2.用@ 和 * 都可以表示数组元素的值

#!/bin/bash 

city=(nanjing [3]=beijing jinan zibo linyi)



for i in ${city[@]}
do

echo $i
done
运行结果:

[root@nn shell]# ./arry1.sh
nanjing
beijing
jinan
zibo
linyi

当然用* 和用@一样。。。当然当数组元素中存在空格基于用引号引起来

${city[@]}   用引号引起来是,“${city[@]}” 和“${city[*]}”有一点不一样的地方就是
“${city[@]}”分行打印,“${city[*]}”在同一行打印
 
  


你可能感兴趣的:(shell)