遍历文件夹中的所有文件

Sea*_*ene 6 command-line bash scripts

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

#!/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/*"
Run Code Online (Sandbox Code Playgroud)

我尝试以这种方式测试脚本:

#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
Run Code Online (Sandbox Code Playgroud)

但它不起作用,这是错误:

ls: cannot access /home/user/Documents/test: No such file or directory
ls: cannot access folder/*: No such file or directory
Run Code Online (Sandbox Code Playgroud)

如何修改脚本来实现呢?

ter*_*don 6

首先,不要解析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/*"
Run Code Online (Sandbox Code Playgroud)

但是,如果您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"
Run Code Online (Sandbox Code Playgroud)


小智 4

为什么你要走那么远,保持简单就可以了

#!/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"
Run Code Online (Sandbox Code Playgroud)

希望有帮助;)