如何遍历存储在变量中的目录路径

时间:2014-11-06 00:01:48

标签: bash

我正在教我的自我bash并尝试创建一个脚本,它将遍历给定目录(或当前目录,如果没有提供)中包含的目录。

这是我到目前为止的脚本:

#!/bin/bash
start_dir=${1:-`pwd`}       # set to current directory or user supplied directory
echo start_dir=$start_dir

for d in $start_dir ; do
    echo dir=$d
done

首先,所有这个脚本当前都是将d设置为start_dir,然后回显start_dir中的值。我想这是有道理的,但我希望它实际上会遍历目录。如何让它实际循环遍历start_dir变量中的目录?

另外,我想要只遍历目录。 This answer表示在路径后放置/将确保只有目录返回到for循环。有没有办法合并这个以确保循环start_dir只会返回目录,因为用户可能不会提供脚本的目录路径?

干杯

1 个答案:

答案 0 :(得分:5)

该示例使用了glob,您也可以:

#!/bin/bash
start_dir=${1:-`pwd`}       # set to current directory or user supplied directory
echo "start_dir=$start_dir"

for d in "$start_dir"/*/ ; do
    echo "dir=$d"
done

*不是目录名,只是表示“任何字符串”。 Bash扩展它以查找与模式匹配的所有路径。

相关问题