循环遍历文件夹中的所有文件

循环遍历文件夹中的所有文件

我正在编写一个脚本来获取文件夹(包括子文件夹)内的所有文件:

#!/bin/bash
function loop() {
files=`ls -1Fd $1`
echo "$files" |
while IFS= read -r file; do
    if [[ "$file" == */ ]]; then
        loop "$file*"
    else
        echo "$file"
    fi
done
}
loop "$PWD/*"

我尝试通过以下方式测试该脚本:

#create folders and files
mkdir test\ folder && mkdir test\ folder/test\ subfolder && touch test\ folder/test\ subfolder/test\ file && cd test\ folder

#execute the script
~/path_to_the_script/test.sh

但是它不起作用,错误如下:

ls: cannot access /home/user/Documents/test: No such file or directory
ls: cannot access folder/*: No such file or directory

如何修改脚本来实现呢?

答案1

首先,不解析ls。现在,脚本失败的原因是因为您正在传递"$PWD/*"。因为这是 qupted,它将在传递给函数之前被扩展,并且由于您的 中/path/to/dir/*没有命名的文件,因此它会失败。*PWD

然而,即使它有效,也会让你陷入无限循环。

您正在寻找的是:

#!/bin/bash

function loop() {
    ## Do nothing if * doesn't match anything.
    ## This is needed for empty directories, otherwise
    ## "foo/*" expands to the literal string "foo/*"/
    shopt -s nullglob

    for file in $1
    do
    ## If $file is a directory
    if [ -d "$file" ]
    then
            echo "looping for $file"
        loop "$file/*"
    else
            echo "$file"
    fi
    done
}
loop "$PWD/*"

但是,如果你的命令PWD包含任何空格字符,那么这个命令就会失败。更安全的方法是:

#!/bin/bash

function loop() {
    ## Do nothing if * doesn't match anything.
    ## This is needed for empty directories, otherwise
    ## "foo/*" expands to the literal string "foo/*"/
    shopt -s nullglob

    ## Make ** recurse into subdirectories
    shopt -s globstar

    for file in "$@"/**
    do
    ## If $file is a file
    if [ -f "$file" ]
    then
        echo "$file"
    fi
    done
}
loop "$PWD"

答案2

你何必绕那么多弯路,简单点就好

#!/bin/bash
function loop() { 
    for i in "$1"/*
    do
        if [ -d "$i" ]; then
            loop "$i"
        elif [ -e "$i" ]; then
            echo $i
        else
            echo "$i"" - Folder Empty"
        fi
    done
}
loop "$PWD"

希望有帮助;)

相关内容