加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

BASH:编写脚本以递归方式移动N级目录

发布时间:2020-12-15 18:30:47 所属栏目:安全 来源:网络整理
导读:我有以下目录结构,例如: /test_dir/d/test_dir/d/cron/test_dir/d/cache/test_dir/d/...(more sub dirs)/test_dir/tree/test_dir/tree/a/test_dir/tree/a/a1/test_dir/tree/a/a2...(and so on for b/ and c/ ) 我编写了以下bash脚本,它有效地传递到/ test_d
我有以下目录结构,例如:
/test_dir/d
/test_dir/d/cron
/test_dir/d/cache
/test_dir/d/...(more sub dirs)
/test_dir/tree
/test_dir/tree/a
/test_dir/tree/a/a1
/test_dir/tree/a/a2
...(and so on for b/ and c/ )

我编写了以下bash脚本,它有效地传递到/ test_dir的第二级,因此它将到达/ test_dir / d / cron或/ test_dir / tree / a但不会更进一步.我无法弄清楚为什么递归脚本不会进一步传播有人请调试脚本并指出我的错误?

这是我写的:

#!/bin/bash

#script to recursively travel a dir of n levels

function traverse() {   

for file in `ls $1`
do
    #current=${1}{$file}
    if [ ! -d ${1}${file} ] ; then
        echo " ${1}${file} is a file"
    else
        #echo "entering recursion with: ${1}${file}"
            traverse "${1}/${file}"
    fi
done
}

function main() {
    traverse $1
}

main $1

这是输出:

/test_dir/a is a file
/test_dir/b is a file
/test_dir//dcache is a file
/test_dir//dcron is a file
/test_dir//dgames is a file
/test_dir//dlib is a file
/test_dir//dlog is a file
/test_dir//drun is a file
/test_dir//dtmp is a file
/test_dir/movies is a file
/test_dir//treea is a file
/test_dir//treeb is a file
/test_dir//treec is a file
/test_dir//treed is a file

我知道可能有更优雅的一行命令来做到这一点.但我试图以这种明确的方式做到这一点.我为这篇文章的篇幅道歉.

编辑:使用遍历“${1} / ${file}”

脚本有几个问题.它应该是这样的:
#!/bin/bash

#script to recursively travel a dir of n levels

function traverse() {
for file in "$1"/*
do
    if [ ! -d "${file}" ] ; then
        echo "${file} is a file"
    else
        echo "entering recursion with: ${file}"
        traverse "${file}"
    fi
done
}

function main() {
    traverse "$1"
}

main "$1"

但是,递归遍历目录的正确方法是使用find命令:

find . -print0 | while IFS= read -r -d '' file
do 
    echo "$file"
done

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读