- 论坛徽章:
- 0
|
①支持双参数格式,即./naivefind filename./naivefind /etc/xxxx filename
②统计搜索到的文件个数并显示出显示结果的绝对路径和名称
③判断/etc/xxxx 是否存在,不存在的话就提示错误,而不是简单的从当前目录下搜索,因为这样做也许是画蛇添足,比如我当前目录下文件非常多,搜索要半天,而用户只是由于输入错误,而你非要给用户在当前目录搜索,显然是不必要的.
④很多人find shell程序在遇到存在无权限访问的文件夹时会死循环,不断的试图进入,但却无法进入,在这里我做除了了异常处理,如果存在这个文件夹但却进不去,那我自动去选择下一个文件夹做递归,而给出无法进入的文件夹路径,当然shell 本身可以提示你没有访问权限.但是如果不处理的话,死循环仍然无法避免,除非改设计.
④但是利用递归效率不高,因为存在多级子目录,而且文件比较多时,效率很低.需要等待很长时间
#!/bin/sh
#Naive Find for Linux 2.4.18
#written by magicgiant CS NJU http://magicgiant.blog@bbs.nju.edu.cn/
#wriitten for OS Experiment 1
#/^ ^\
# (..) ZZZzzzzz.......
#FF is a sub function that maches the dir or the file
FF(){
#get name of file or dir from the list
for I in $(ls|tr '\n' ' ')
do
if [ "$I" == "$FN" ]
then echo "$PWD"/"$FN"
#one found ,count increases
count=$((count+1))
fi
done
}
REC(){
#SB is the sub dir of the dir that the programm in
for SB in $(ls -F|grep '/$'|sed 's/\$//'|tr '\n' ' ')
do
#i think pwd1 and pwd2 is the best in the shell,here they used for the case that one dir you have no right to visit.and then we can jump the dir to the #next one.if not ,the shell will go into a dead circul,it'll try again and again to go into the dir,but fail foever
pwd1=$PWD
cd $SB
pwd2=$PWD
if [ "$pwd1"!="$pwd2" ] ;
then
FF
REC
cd ..
else
echo "$PWD"/"$SB"/"you may not have the right or somthing else to visit!"
fi
done
}
#for the case that ./naivefind filename style
WU(){
FF
REC
}
#for the case that ./naivefind /etc/xxxx filename style ,in this naive shell ,it is the same as the function WU,but in advanced shell it'll be different
YOU(){
FF
REC
}
#in the beginning ,count = 0
count=0
#we can judge $2,here is a trick.for I don't know how to write the case that $2 is NULL,so I use $3 as the judgement
case $2 in
`echo "$3" `)
#FN =$1
FN=$1
WU;;
#$2 is not NULL
*)
FN=$2
#here pwd1 and pwd2 used for the cases that ./naivefind /etc/xxxx fliename ,whichi /etc/xxxx is not exist.though it can find filename from the dir #wherethe shell stand in,but it is not clever.it sometimes may be " hua she tian zu "------a snake but you give it feet.
pwd1=$PWD
cd $1
pwd2=$PWD
if [ "$pwd1" = "$pwd2" ];
then
#judge if the dir you give $1 exists
echo " lease make sure that you have input a right dir!"
exit
fi
YOU;;
esac
#judge count and output different message!
case $count in
0)
echo "There is no such file!"
;;
*)
echo "There is "$count" files found!"
;;
esac |
|