今天在书上看到了一个关联数组 let statarray["$ftype"]++ 这样一个操作,用来做索引的自增统计,所以记下来
#!/bin/bash #统计文件类型 #关于关联数组 用let ++ 值自增的验证 if [ $# -ne 1 ]; then echo "Usage is $0 basepath"; exit fi path=$1 declare -A statarray; #定义一个关联数组 for line in $(find $path -type f -print) #通过 find的-print 将输出给for循环 do ftype=`file -b "$line" | cut -d , -f1` #通过file命令获取文件类型,并赋值给ftype let statarray["$ftype"]++; #自增操作,此处有疑问,关联数组的赋值也是直接在本条语句中赋值的吗? echo "$ftype:${statarray["$ftype"]}" done echo ================= file types and counts ===================== for ftype in "${!statarray[@]}"; do echo $ftype : ${statarray["$ftype"]} done
输出结果:
wyf349@ubuntu:~/user/study_shell$ ./filestat.sh /home/wyf349/user/study_shell ASCII text:1 UTF-8 Unicode text:1 UTF-8 Unicode text:2 ASCII text:2 #由输出结果可知,对应索引值为ASCII的值,在做自增操作。 empty :1 ASCII text:3 empty :2 ASCII text:4 Bourne-Again shell script:1 ASCII text:5 ASCII text:6 ASCII text:7 Bourne-Again shell script:2 ASCII text:8 Bourne-Again shell script:3 ASCII text:9 UTF-8 Unicode text:3 Bourne-Again shell script:4 Bourne-Again shell script:5 ASCII text:10 ASCII text:11 ================= file types and counts ===================== empty : 2 Bourne-Again shell script : 5 ASCII text : 11 UTF-8 Unicode text : 3