【问题标题】:Simulating the find command: why is my code not recursing correctly?模拟 find 命令:为什么我的代码不能正确递归?
【发布时间】:2024-04-26 18:05:01
【问题描述】:

我的任务是编写一个 Unix shell 脚本,询问用户目录的名称,然后像find 一样工作。

这是我目前所拥有的:

#!/bin/bash
dir_lister()
{
    cd "$1"
    echo "$1"
    list=$(ls -l ${1})


    nolines=$(echo "$list" | awk 'END{printf "%d",NF}')

    if [ $nolines -eq 2 ]
    then

        echo "$1"

        return
    fi

    filelist=$(echo "$list" | grep ^-.*)
    dirlist=$(echo "$list" | grep ^d.*)

    filename=$(echo "$filelist"| awk '{printf "%s\n",$NF}')
    present=$(pwd)
    echo "$filename"| awk -v pres=$present '{printf "%s/%s\n",pres,$0}'

    dirlist2=$(echo "$dirlist" | awk '{printf "%s\n",$NF}')

    echo "$dirlist2" | while IFS= read -r line;
    do
        nextCall=$(echo "$present/$line");
        dir_lister $nextCall;
        cd ".."
    done
    cd ".."
}



read -p "Enter the name of the direcotry: " dName

dir_lister $dName 

问题是,在三个目录的深度之后,这个脚本进入了一个无限循环,我不明白为什么。

编辑:

这是我在查看您的答案后想出的代码,它仍然没有超过 1 个目录深度:

#!/bin/bash

shopt -s dotglob # don't miss "hidden files"
shopt -s nullglob # don't fail on empty directories


list_directory()
{
    cd "$2"
    cd "$1"
    ##echo -e "I am called \t $1 \t $2"
    for fileName in "$1/"* 
    do
        ##echo -e "hello \t $fileName"
        if [ -d "$fileName" ];
        then
            echo "$fileName"
            list_directory $fileName $2

        else
            echo "$fileName"
        fi
    done

}
read -p "Enter the direcotory Name: " dirName
var=$(pwd)
list_directory $dirName $var

【问题讨论】:

  • 为什么需要“模拟”find 而不是只使用find?你的问题在哪里?
  • @jordanm 这是我作业的一部分
  • 问题没有说明实际问题是什么
  • 请查看我对我的问题所做的更改
  • 我不知道无限循环,但如果你先cd $1 然后ls $1 你不会得到你认为的文件列表。

标签: bash shell directory


【解决方案1】:

好的,这是在目录中列出文件的完全错误的方式(请参阅ParsingLs)。我会给你这些片段,你应该能够将它们组合成一个工作脚本。

把它放在脚本的顶部:

shopt -s dotglob # don't miss "hidden files"
shopt -s nullglob # don't fail on empty directories

然后您可以轻松地遍历目录内容:

for file in "$directory/"* ; do
   #...
done

测试是否有目录:

if [ -d "$file" ] ; then
   # "$file" is a directory, recurse...
fi

【讨论】:

  • 我在看到你的回答后添加了我想出的代码,但它仍然有问题。在他们结束这个问题之前,你能告诉我我的代码有什么问题吗?
  • @sasidhar 你不需要cd
最近更新 更多