2、递归遍历文件夹下每一个文件

#!/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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值