#!/bin/bash
# 获取关键路径:$0是启动的脚本名,dirname $0 是脚本所在的文件夹
cd `dirname $0`
workDir=`pwd`
scriptName=$0
basePath=$1
# 判断启动脚本是是否输入了集群机器列表文件
while true
do
if [[ ${#basePath} -eq 0 ]]; then
read -p "请输入需要遍历的文件路径:" basePath
fi
# 判断集群列表文件是否是绝对路径,如果不是则转化为绝对路径
if [[ ${basePath:0:1} != "/" ]]; then
basePath=$workDir/$basePath
fi
if [ ! -e $basePath ]; then
echo "输入的路径{ ${basePath} } 不存在,请重新输入:"
read basePath
continue
fi
break
done
# 递归遍历每一个文件夹
# 优先处理文件,用childDirPaths来记录文件夹,之后再处理
# 注意:childDirPaths=()不能放在方法外面,否则他的值会不断积累,程序没法停止
scanEveryDirFirstFile(){
echo $1
if [ -d $1 ]; then
childDirPaths=()
index=0
for childPath in $1/*; do
if [ -d $childPath ]; then
childDirPaths[$index]=$childPath
let index++
else
echo $childPath
fi
done
# 继续遍历子文件夹下的信息
for childDir in ${childDirPaths[@]}; do
scanEveryDirFirstFile $childDir
done
fi
}
# 递归遍历每一个文件夹
# 没有先后之分,遇到什么就处理什么
scanEveryDirRandom(){
echo $1
if [ -d $1 ]; then
for childPath in $1/*; do
if [ -d $childPath ]; then
scanEveryDirRandom $childPath
else
echo $childPath
fi
done
fi
}
scanEveryDirFirstFile $basePath
echo ""
scanEveryDirRandom $basePath
# 总结
1、最好不要用隧道,因为隧道是使用另一个shell进程,不能给当前变量赋值
2、用于保存dir的变量,要放在方法里面作为局部变量
转载于:https://my.oschina.net/liufukin/blog/2218970