我怎么能存储在一个阵列目录列表? [英] How can I store a list of directories in an array?
本文介绍了我怎么能存储在一个阵列目录列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么这个没有列出什么?谢谢
文件夹=()LS的/ tmp /备份/ |而读DIR
做
FOLDER + =($ DIR)
DONE回声$ {FOLDER [1]}
解决方案
分析
您示例是要失败的。例如:
- 请不要解析
LS
。 的输出 - 请不要承担目录的每个条目是一个目录。
- 请不要追加在循环数组没有一个很好的理由。
- 请不要使用未加引号的变量。
使用shell通配符
假设在/ tmp /备份的每个条目是一个目录,你可以简单地使用shell通配符来填充数组。如果你可以有文件以及目录条目,那么你需要使用的找到的或使用壳体试验前pression以确保条目实际上是一个目录。例如:
#启用特殊处理,以prevent扩展到
#文字'/ tmp目录/备份/ *时,没有找到匹配。
禁用了javascript -s nullglobFOLDERS =(/ tmp目录/备份/ *)
在$文件夹[@]文件夹;做
[-d$文件夹]]&放大器;&安培;回声$文件夹
结束
Why this does not list anything? Thank you
FOLDER=()
ls /tmp/backup/ | while read DIR
do
FOLDER+=("$DIR")
done
echo ${FOLDER[1]}
解决方案
Analysis
Your example is designed to fail. For example:
- Don't parse the output of
ls
. - Don't assume every entry in a directory is a directory.
- Don't append arrays in a loop without a good reason.
- Don't use unquoted variables.
Use Shell Globs
Assuming that every entry in /tmp/backup is a directory, you can simply use shell globs to populate your array. If you may have files as well as directory entries, then you'll need to use find or use a shell test expression to ensure that the entry is actually a directory. For example:
# Enable special handling to prevent expansion to a
# literal '/tmp/backup/*' when no matches are found.
shopt -s nullglob
FOLDERS=(/tmp/backup/*)
for folder in "$FOLDERS[@]"; do
[[ -d "$folder" ]] && echo "$folder"
end
这篇关于我怎么能存储在一个阵列目录列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文