shell之关联数组

1、将密码文件的每一行作为元数赋值给数组

[root@master script]# vim test4.sh
j=0
for i in `cat /etc/shadow`
do
  array[$j]=$i
  echo ${array[$j]}
  let j++

done

[root@master script]# sh test4.sh 
root:$6$OnS/llYN0j3Y2Epk$uPEeWc6vpcj2fDuSWsrticG/pokdIXjISNXeWTb6ociQXJBfA64jtElSsKXz1wHwBaxWBlT.QNs0JDtC5BlgI1::0:99999:7:::
bin:*:18353:0:99999:7:::
daemon:*:18353:0:99999:7:::
adm:*:18353:0:99999:7:::
lp:*:18353:0:99999:7:::
sync:*:18353:0:99999:7:::
shutdown:*:18353:0:99999:7:::
halt:*:18353:0:99999:7:::
mail:*:18353:0:99999:7:::
operator:*:18353:0:99999:7:::
games:*:18353:0:99999:7:::
ftp:*:18353:0:99999:7:::
nobody:*:18353:0:99999:7:::
systemd-network:!!:19435::::::
dbus:!!:19435::::::
polkitd:!!:19435::::::
sshd:!!:19435::::::
postfix:!!:19435::::::
chrony:!!:19435::::::
...............................................

2、使用关联数组统计密码文件中用户使用的不同类型shell的数量

[root@master script]# vim test45.sh
#!/bin/bash

declare -A array
for i in `cut -d: -f 7 /etc/passwd`
do
        let array[$i]++
done
for i in ${!array[*]}
do
        echo "$i ${array[$i]}"
done

[root@master script]# sh test45.sh 
/sbin/nologin 16
/bin/sync 1
/bin/bash 3
/sbin/shutdown 1
/sbin/halt 1

3、使用关联数组按扩展名统计指定目录中文件的数量 

[root@master script]# vim test5.sh
#!/bin/bash

declare -A array
for i in `ls ~/script/test | awk -F . '{print $NF}'`
do
  let array[$i]++
done
for j in ${!array[*]}
do
  echo "$j ${array[$j]}"
done

[root@master script]# sh test5.sh 
txt 8
exe 9
sh 6
dir 7

你可能感兴趣的:(shell,vim,linux,编辑器,shell,关联数组)