写一个遍历文件夹目录和文件的脚本,默认搜索文件,加上 -d 参数搜索目录,可以设置搜索深度,参数设置模仿find 命令,当然效率没有find命令高,日常使用还是使用find命令,此脚本仅做参考
#! /bin/bash
function IsNumber
{
[ $# -eq 0 ] && return 1
echo $1 | grep -P "^\d+$" > /dev/null
return $?
}
is_dir=0
#判断是否是搜索目录
for p in $@
do
[ "$p" == "-d" ] && is_dir=1 && break
done
while [ $# -gt 0 ]
do
#这里删除不必要的参数
[ "$1" == "-d" ] && shift 1 && continue
if [ "$1" != "-maxdepth" ]; then
new_para[${#new_para[*]}]="$1"
shift 1
else
shift 1
if [ $# -eq 0 ] || ! IsNumber $1; then
echo "参数错误 -maxdepth = $1 ,请检查 !!!" && exit 1
fi
maxdepth="$1" && shift 1
fi
done
#如果是搜索目录,则不会显示被搜索的当前目录
function FindAll
{
local path;local tmp_file;local full_path;local cur_depth
[ $1 -eq 0 ] && return
cur_depth=$1
shift 1
for path in $@
do
if [ $is_dir -eq 1 ]; then
[ ! -d "$path" ] && continue
full_path=$(cd $path && pwd) #防止出现相对路径
for tmp_file in $(cd $full_path && ls -a)
do
[ "$tmp_file" == "." -o "$tmp_file" == ".." ] && continue
[ ! -d "$full_path/$tmp_file" ] && continue
echo "$full_path/$tmp_file"
FindAll $((cur_depth - 1)) "$full_path/$tmp_file"
done
else
[ ! -d "$path" ] && echo "$path" && continue
full_path=$(cd $path && pwd) #防止出现相对路径
for tmp_file in $(cd $full_path && ls -a)
do
[ "$tmp_file" == "." -o "$tmp_file" == ".." ] && continue
[ ! -d "$full_path/$tmp_file" ] && echo "$full_path/$tmp_file" && continue
FindAll $((cur_depth - 1)) "$full_path/$tmp_file"
done
fi
done
}
FindAll ${maxdepth:="-1"} ${new_para[*]}
脚本名字命名为display.sh ,执行chmod a+x display.sh
例如: ./display.sh ./ -d -maxdepth 2 此命令等同于 find ./ -maxdepth 2 -type d ,执行的结果一致,除了find命令会显示参数传入的目录本身,此脚本不会显示参数传入的目录,只显示所有的子目录
如果搜索所有的文件 ./display.sh ./
如果搜索所有的文件夹 ./display.sh ./ -d