如何在数组中存储目录列表?

Cha*_*lie 2 arrays directory bash

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

FOLDER=()

ls /tmp/backup/ | while read DIR
do
    FOLDER+=("$DIR")
done

echo ${FOLDER[1]}
Run Code Online (Sandbox Code Playgroud)

Tod*_*obs 8

分析

您的示例旨在失败.例如:

  • 不要解析输出ls.
  • 不要假设目录中的每个条目都是目录.
  • 没有充分理由不要在循环中附加数组.
  • 不要使用不带引号的变量.

使用Shell Globs

假设/ tmp/backup中的每个条目都是一个目录,您只需使用shell globs来填充数组.如果您可能有文件和目录条目,那么您将需要使用查找或使用shell测试表达式来确保该条目实际上是一个目录.例如:

# 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
Run Code Online (Sandbox Code Playgroud)

  • 不要调用目录文件夹!;-) (3认同)