使用Bash给定路径中存在的目录列表填充数组

时间:2018-09-11 12:30:38

标签: arrays bash listdir

我有一个目录路径,其中有多个文件和目录。

我想使用基本的bash脚本创建仅包含目录列表的数组。

假设我有一个目录路径: /my/directory/path/

$ls /my/directory/path/
a.txt dirX b.txt dirY dirZ

现在,我想只用目录(即arr[]dirXdirY填充名为dirZ的数组。

有一个post,但与我的要求无关。

任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:2)

尝试一下:

#!/bin/bash
arr=(/my/directory/path/*/)    # This creates an array of the full paths to all subdirs
arr=("${arr[@]%/}")            # This removes the trailing slash on each item
arr=("${arr[@]##*/}")          # This removes the path prefix, leaving just the dir names

与基于ls的答案不同,它不会被包含空格,通配符等的目录名称所混淆。

答案 1 :(得分:1)

尝试:

shopt -s nullglob   # Globs that match nothing expand to nothing
shopt -s dotglob    # Expanded globs include names that start with '.'

arr=()
for dir in /my/directory/path/*/ ; do
    dir2=${dir%/}       # Remove the trailing /
    dir3=${dir2##*/}    # Remove everything up to, and including, the last /
    arr+=( "$dir3" )
done