BASH:编写脚本以递归旅行氮水平的目录

编程入门 行业动态 更新时间:2024-10-26 06:26:44
本文介绍了BASH:编写脚本以递归旅行氮水平的目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有以下的目录结构,例如:

I have the following directory structure for example:

/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 /树/ A ,但不会走得更远。我想不通,为什么递归脚本将不会进一步旅行可以有人请调试脚本,并指出我的错误?

I've written the following bash script that effectively travels to the second level of /test_dir so it will reach /test_dir/d/cron or /test_dir/tree/a but will not go further. I cannot figure out why the recursive script will not travel further can someone please debug the script and point out my error?

这里是我写的:

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

我知道有可能更优雅的一行命令来做到这一点。但是我试图做到这一点在这个明确的方式。我对这个职位的长度道歉。

I know there are probably more elegant one line commands to do this. But im trying to do it in this explicit manner. I apologize for the length of this post.

编辑:使用横$ {1} / $ {}文件

推荐答案

若干问题的脚本。它应该是这样的:

Several problems with the script. It should be like this:

#!/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命令:

However, the correct way to recursively traverse a directory is by using the find command:

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

更多推荐

BASH:编写脚本以递归旅行氮水平的目录

本文发布于:2023-10-28 13:20:07,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1536747.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:递归   脚本   水平   旅行   目录

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!