linux - bash 列出当前文件夹中的子文件夹没有给出预期的结果 [只给出第一个文件夹]

标签 linux bash

我尝试列出子文件夹并将它们作为列表保存到变量

DIRS=($(find . -maxdepth 1 -mindepth 1 -type d ))

之后我想在子文件夹中做一些工作。即

for item in $DIRS
 do     
echo $item

但是之后

echo $DIRS

它只给出第一项(子文件夹)。有人可以指出我的错误或提出其他解决方案吗?

最佳答案

以下创建了一个 bash 数组,但只列出了三个子目录之一:

$ dirs=($(find . -maxdepth 1 -mindepth 1 -type d ))
$ echo $dirs
./subdir2

要查看所有目录,必须使用[@][*]下标形式:

$ echo "${dirs[@]}"
./subdir2 ./subdir1 ./subdir3

或者,在循环中使用它:

$ for item in "${dirs[@]}"; do echo $item; done
./subdir2
./subdir1
./subdir3

避免分词问题

请注意,在上面的代码中,shell 在创建数组之前执行分词。因此,如果任何子目录的名称中包含空格,此方法将失败。

  1. 即使名称中包含空格、制表符或换行符,以下内容也将成功创建子目录名称数组:

    dirs=(*/)
    
  2. 如果您需要使用 find 并且希望它对困难的文件名是安全的,那么请使用 find 的 --exec 选项。

文档

$dirs 形式只返回数组的第一个元素。这记录在 man bash 中:

Referencing an array variable without a subscript is equivalent to referencing the array with a subscript of 0.

[@][*] 的使用也记录在 man bash 中:

Any element of an array may be referenced using ${name[subscript]}. The braces are required to avoid conflicts with pathname expansion. If subscript is @ or , the word expands to all members of name. These subscripts differ only when the word appears within double quotes. If the word is double-quoted, ${name[]} expands to a single word with the value of each array member separated by the first character of the IFS special variable, and ${name[@]} expands each element of name to a separate word.

关于linux - bash 列出当前文件夹中的子文件夹没有给出预期的结果 [只给出第一个文件夹],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29056451/

相关文章:

linux - 在 Debian 机器上安装 Windows DFS 共享

linux - 找不到 Bash 中的数组

linux - 如何检测 bash 中是否正在运行 i3-wm 或是否正在运行 GNOME

linux - debian - lampp - 在 sublime 和权限中打开文件

c - Valgrind 内存检查输出

linux - 使用 awk 的脚本中出现未知错误

bash - 使用 wget 从站点下载类似文件

bash - 是否有一个函数可以让我在文本文件中的一组行的开头添加一个字符串?

bash - 读取命令 : Display the prompt in color (or enable interpretation of backslash escapes)

linux - 无法删除共享文件系统中的文件