如何将 ls 分配给 Linux Bash 中的数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18884992/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I assign ls to an array in Linux Bash?
提问by Jordin Youssef
array=${ls -d */}
echo ${array[@]}
I have three directories: ww
ee
qq
. I want them in an array and then print the array.
我有三个目录:ww
ee
qq
. 我希望它们在一个数组中,然后打印该数组。
回答by Aaron Okano
It would be this
就是这个
array=($(ls -d */))
EDIT: See Gordon Davisson's solution for a more general answer (i.e. if your filenames contain special characters). This answer is merely a syntax correction.
编辑:请参阅 Gordon Davisson 的解决方案以获得更一般的答案(即,如果您的文件名包含特殊字符)。这个答案只是语法更正。
回答by Gordon Davisson
Whenever possible, you should avoid parsing the output of ls
(see Greg's wiki on the subject). Basically, the output of ls
will be ambiguous if there are funny characters in any of the filenames. It's also usually a waste of time. In this case, when you execute ls -d */
, what happens is that the shell expands */
to a list of subdirectories (which is already exactly what you want), passes that list as arguments to ls -d
, which looks at each one, says "yep, that's a directory all right" and prints it (in an inconsistent and sometimes ambiguous format). The ls
command isn't doing anything useful!
只要有可能,您应该避免解析输出ls
(请参阅关于主题的 Greg 维基)。基本上,ls
如果任何文件名中有有趣的字符, 的输出将是模棱两可的。这通常也是浪费时间。在这种情况下,当您执行 时ls -d */
,会发生 shell 扩展*/
到子目录列表(这正是您想要的),将该列表作为参数传递给ls -d
,它查看每个子目录,说“是的,那是一个目录好吧”并打印它(以不一致且有时模棱两可的格式)。该ls
命令没有做任何有用的事情!
Well, ok, it is doing one thing that's useful: if there are no subdirectories, */
will get left as is, ls
will look for a subdirectory named "*", not find it, print an error message that it doesn't exist (to stderr), and notprint the "*/" (to stdout).
好吧,它正在做一件有用的事情:如果没有子目录,*/
将保持原样,ls
将查找名为“*”的子目录,找不到它,打印一条错误消息它不存在(以stderr),而不是打印“*/”(到标准输出)。
The cleaner way to make an array of subdirectory names is to use the glob (*/
) withoutpassing it to ls
. But in order to avoid putting "*/" in the array if there are no actual subdirectories, you should set nullglob first (again, see Greg's wiki):
制作子目录名称数组的更简洁方法是使用 glob( */
)而不将其传递给ls
. 但是为了避免在没有实际子目录的情况下将“*/”放入数组中,您应该首先设置 nullglob(再次参见Greg 的 wiki):
shopt -s nullglob
array=(*/)
shopt -u nullglob # Turn off nullglob to make sure it doesn't interfere with anything later
echo "${array[@]}" # Note double-quotes to avoid extra parsing of funny characters in filenames
If you want to print an error message if there are no subdirectories, you're better off doing it yourself:
如果你想在没有子目录的情况下打印错误消息,最好自己做:
if (( ${#array[@]} == 0 )); then
echo "No subdirectories found" >&2
fi
回答by konsolebox
This would print the files in those directories line by line.
这将逐行打印这些目录中的文件。
array=(ww/* ee/* qq/*)
printf "%s\n" "${array[@]}"