如何创建包含文件夹中所有文件名称的数组?

时间:2018-07-05 12:50:16

标签: bash

给一个文件夹(我的脚本将这个文件夹的名称作为参数),如何创建一个数组,其中将包含该文件夹中所有文件的名称(以及该文件夹中任何文件夹和其他文件夹-递归)?

我试图那样做:

#!/bin/bash

function get_all_the_files {
for i in "${1}"/*; do
         if [ -d "$i" ]; then 
            get_all_the_files ${1}
         else
            if [ -f "${i}" ]; then
                arrayNamesOfAllTheFiles=(${arrayNamesOfAllTheFiles[@]} "${i}")
            fi
         fi
done
}

arrayNamesOfAllTheFiles=()

get_all_the_files folder

declare -p arrayNamesOfAllTheFiles

但是它不起作用。有什么问题,我该如何解决?

2 个答案:

答案 0 :(得分:3)

要坚持设计(在文件上循环并仅插入常规文件),在每一步中填充数组,但让Bash通过glob执行递归,则可以使用以下代码:

# the globstar shell option enables the ** glob pattern for recursion
shopt -s globstar

# the nullglob shell option makes non-matching globs expand to nothing (recommended)
shopt -s nullglob

array=()

for file in /path/to/folder/**; do
    if [[ ! -h $file && -f $file ]]; then
        array+=( "$file" )
    fi
done

通过测试[[ ! -h $file && -f $file ]],我们测试文件不是符号链接和常规文件(如果不测试文件不是符号链接,您还将拥有解析为常规文件的符号链接。 )。

您还了解了将array+=( "stuff" )模式而不是array=( "${array[@]}" "stuff" )附加到数组的方法。


另一种可能性(使用Bash≥4.4,其中实现了-d的{​​{1}}选项)和GNU mapfile(支持find谓词):

-print0

答案 1 :(得分:2)

您几乎正确。递归调用中有一个小的错字:

    if [ -d "$i" ]; then 
        get_all_the_files ${1}
    else

应该是

    if [ -d "$i" ]; then 
        get_all_the_files ${i}
    else

我要补充一点的是,bash中像这样的数组的使用非常简单。如果您尝试使用文件的递归树,则通常使用findxargs之类的工具。

find . -type f -print0 | xargs -0 command-or-script-to-run-on-each-file