我尝试列出子文件夹并将它们作为列表保存到变量
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 在创建数组之前执行分词。因此,如果任何子目录的名称中包含空格,此方法将失败。
即使名称中包含空格、制表符或换行符,以下内容也将成功创建子目录名称数组:
dirs=(*/)
如果您需要使用
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/