转载自:http://falcon-dgb.spaces.live.com/Blog/cns!5566E2215E60F837!1207.entry
在shell脚本编程中,数组是我们保存和处理信息的一种有效工具。本文简单介绍一下在bash和ksh中数组使用的异同。 * 数组的定义 o 其实bash和ksh在数组使用上的主要区别就在于数组定义方式的不同。 o bash + bash中数组定义采用形式: arr =(element1 element2 element3...... )。下面的例子将当前目录下文件名存入数组files中。 view plaincopy to clipboardprint? 1. #ls 2. iostat.out mpstat.out sar-d.out sar.post vmstat.out 3. #files=($(ls)) o ksh + ksh中数组定义采用形式: set -A arr element1 element2 element3 ...... 。下面的例子实现与上例同样的功能。 view plaincopy to clipboardprint? 1. #ls 2. iostat.out mpstat.out sar-d.out sar.post vmstat.out 3. #set -A files $(ls) * 数组的访问 o 数组的访问主要包括: 获取数组中元素的个数, 获取特定索引数组元素, 遍历数组元素。在bash和ksh中这些操作基本是相同的。 o 获取数组元素个数 view plaincopy to clipboardprint? 1. #echo ${#files[@]} 2. 5 o 获取特定数组元素 view plaincopy to clipboardprint? 1. #echo ${files[0]} 2. iostat.out 3. #echo ${files[1]} 4. mpstat.out 5. #echo ${files[2]} 6. sar-d.out 7. #echo ${files[3]} 8. sar.post 9. #echo ${files[4]} 10. vmstat.out o 遍历数组元素 view plaincopy to clipboardprint? 1. #for i in ${files[*]}; 2. > do 3. > echo "access file: $i" 4. > ls -lh $i 5. > done 6. access file: iostat.out 7. -rw-r--r-- 1 root root 9.8K Nov 26 16:37 iostat.out 8. access file: mpstat.out 9. -rw-r--r-- 1 root root 6.4K Nov 26 16:37 mpstat.out 10. access file: sar-d.out 11. -rw-r--r-- 1 root root 29K Nov 26 16:37 sar-d.out 12. access file: sar.post 13. -rw-r--r-- 1 root root 101K Nov 26 16:37 sar.post 14. access file: vmstat.out 15. -rw-r--r-- 1 root root 551 Nov 26 16:37 vmstat.out