在网上看到这个题目
大概意思就是:统计 /etc/passwd文件中有多少种shell及其个数
忙活了三个小时,自己写了个,代码如下:
#!/bin/sh
# get the shell number in the file /etc/passwd
declare -a arr_result
# print the array
print_arr(){
sum=${#arr_result[*]}
echo "total count is :$sum"
for ((i=0;i
do
echo "array num:$i ${arr_result[$i]}"
done
}
while read line
do
shell_name=`echo $line|awk -F":" '{print $7}'`
count=${#arr_result[*]}
#echo "number of arr: ----------------$count"
if [ $count -eq 0 ];then
arr_result[0]=`echo "$shell_name=1"`
else
has=0
for ((i=0;i
do
sub=${arr_result[$i]}
sh_name=`echo $sub|awk -F"=" ' {print $1}'`
sh_num=`echo $sub|awk -F"=" ' {print $2}'`
#echo "arr num is $i----"
#echo -e "suname=$sh_name"
#echo -e "shnum=$sh_num"
if [ "$sh_name" = "$shell_name" ];then
new_num=`expr $sh_num + 1`
#echo "arrhas and newnum=----------$new_num"
arr_result[$i]=`echo $sh_name=$new_num`
has=1
break
fi
done
if [ $has -eq 0 ];then
#echo "arr do not has "
arr_result[$count]=`echo $shell_name=1`
has=0
fi
fi
done < /etc/passwd
print_arr
结果如下:
写完后去看了下答案,悲摧了,答案只有一行代码,如下:
awk -F":" '{print $NF}' /etc/passwd |uniq -c
结果如下:
悲摧过后,对比了下结果,发现答案里的方法不能完全表达题目的意思。当相同的shell被分割开时,统计结果被分开了。
想想自己三小时写的代码,几秒钟就ok了,太受打击了。