linux shell 数组的长度计算、修改、循环输出等操作


From :http://blog.csdn.net/snrqtdhuqf/article/details/7242309 

在shell中,数组变量的赋值有两种方法:

(1) name = (value1 ... valuen)此时下标从0开始

(2) name[index] = value

 example:

  1. #!/bin/sh  
  2. #arrayTest  
  3. name=(yunix yhx yfj)  
  4. echo "array is:${name[@]}"  
  5. echo "array length is:${#name[*]}"  
  6. echo ${name[1]}  
  7. name[1]=yang  
  8. echo ${name[1]}  
  9. read -a name  
  10. echo ${name[1]}  
  11. echo "loop the array"  
  12. len=${#name[*]}  
  13. i=0  
  14. while [ $i -lt $len ]  
  15. do  
  16. echo ${name[$i]}  
  17. let i++  
  18. done  

result:

array is:yunix yhx yfj
array length is:3
yhx
yang
a b c d e
b
loop the array
a
b
c
d
e

 

下面的是关于数组的输出实例

example:

 

#!/bin/sh  

  1. #arrayLoopOut  
  2. read -a array  
  3. len=${#array[*]}  
  4. echo "array's length is $len"  
  5. echo "use while out the array:"  
  6. i=0  
  7. while [ $i -lt $len ]  
  8. do  
  9.         echo -n "${array[$i]}"  
  10. let i++  
  11. done  
  12. echo  
  13. echo "use for out the array:"  
  14. for ((j=0;j<"$len";j=j+1))  
  15. do  
  16.         echo -n ${array[$j]}  
  17. done  
  18. echo  
  19. echo "use for in out the array:"  
  20. for value in ${array[*]}  
  21. do  
  22. echo -n $value  
  23. done  

result:

a b c d e f g
array's length is 7
use while out the array:
abcdefg
use for out the array:
abcdefg
use for in out the array:
abcdefg


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM