0

我的任务是编写一个 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
4

1 回答 1

2

好的,这是在目录中列出文件的完全错误的方法(请参阅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
于 2012-08-10T21:07:06.960 回答