Linux shell 遍历文件夹文件和目录的脚本

写一个遍历文件夹目录和文件的脚本,默认搜索文件,加上 -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

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值