简体   繁体   English

在shell脚本中使用for循环遍历目录结构

[英]Traverse a directory structure using a for loop in shell scripting

I am looking to traverse a directory using a conditional for / while Loop 我期待使用条件for / while循环遍历目录

Scenario : path is /home/ABCD/apple/ball/car/divider.txt 场景:路径是/home/ABCD/apple/ball/car/divider.txt

Say I always start my program from /home I need to iterate from home -- > ABCD --> apple --> ball --> car --> divider.txt 说我总是从/ home开始我的程序我需要从家里迭代 - > ABCD - > apple - > ball - > car - > divider.txt

Every time I iterate, check if the obtained path is a directory or a file, if file exit the loop and return me the path if the returned path is directory, loop one more round and continue.. 每次迭代时,检查获取的路径是目录还是文件,如果文件退出循环并返回路径,如果返回的路径是目录,则循环一轮并继续..

Updated question 更新的问题

FILES="home"
for f in $FILES
do

    echo "Processing $f"  >> "I get ABCD as output
        if[-d $f]
  --> returns true, in my next loop, I should get the output as /home/ABCD/apple..
        else 
          Break;
        fi

done

after I exit the for loop, I should have the /home/ABCD/apple/ball/car/ as output 退出for循环后,我应该将/ home / ABCD / apple / ball / car /作为输出

Besides the multi-purpose find you might also want to take a look at tree . 除了多功能find您可能还想看看tree It will list contents of directories in a tree-like format . 它将以树状格式列出目录的内容

$ tree -F /home/ABCD/
/home/ABCD/
`-- apple/
    `-- ball/
        `-- car/
            `-- divider.txt

3 directories, 1 file

This is the way I have implemented to get it working 这是我实现它的方式来实现它

for names in $(find /tmp/files/ -type f); 
do
    echo " ${directoryName} -- Directory Name found after find command : names" 

    <== Do your Processing here  ==>

done

Names will have each file with the complete folder level 名称将使每个文件具有完整的文件夹级别

/tmp/files is the folder under which I am finding the files / tmp / files是我在其中找到文件的文件夹

find /home -type d

will give you all the directories under /home and nothing else. 会给你/ home下的所有目录而不是别的。 replace /home with the directory of your choice and you will get directories under that level. 将/ home替换为您选择的目录,您将获得该级别下的目录。

if your heart is set on checking every file one by one, the if..then test condition you are looking for is : 如果您的心脏一个接一个地检查每个文件,那么您正在寻找的if..then测试条件是:

if [ -f $FILE ]
then
echo "this is a regular file"
else 
echo "this is not a regular file, but it might be a special file, a pipe etc."
fi

-or- -要么-

if [ -d $FILE ]
then
echo "this is a directory. Your search should go further"
else 
echo "this is a file and buck stops here"
fi

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM