如何在数组中存储目录列表? [英] How can I store a list of directories in an array?

查看:148
本文介绍了如何在数组中存储目录列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这不列出任何东西?谢谢

  FOLDER =()

ls / tmp / backup /同时阅读DIR
do
FOLDER + =($ DIR)
done

echo $ {FOLDER [1]}


解决方案

分析



失败。例如:




  • 不解析 ls 的输出。 >
  • 不要假设目录中的每个条目都是一个目录。

  • 不要在没有正当理由的循环中附加数组。

  • 不要使用未引用的变量。



使用Shell Globs



假设/ tmp / backup中的每个条目都是一个目录,可以简单地使用shell glob来填充你的数组。如果您可能有文件以及目录条目,则需要使用 find 或使用shell测试表达式来确保该条目实际上是一个目录。例如:

 #启用特殊处理以阻止扩展到
#literal'/ tmp / backup / *'当没有找到匹配。
shopt -s nullglob

FOLDERS =(/ tmp / backup / *)
为$ {FOLDERS [@]}中的文件夹; do
[[-d$ folder]]&& echo$ folder
done

#如果需要,使用后取消设置shell选项。 Nullglob
#默认情况下未设置。
shopt -u nullglob


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"
done

# Unset shell option after use, if desired. Nullglob
# is unset by default.
shopt -u nullglob

这篇关于如何在数组中存储目录列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆