如果你使用 GNU find,你可以试试-execdir 参数,例如:
find . -type d -execdir realpath "{}" ';'
或(根据@gniourf_gniourf comment):
find . -type d -execdir sh -c 'printf "%s/%s\n" "$PWD" "$0"' {} \;
注意:你可以使用${0#./}而不是$0来修复前面的./。
或更实际的例子:
find . -name .git -type d -execdir git pull -v ';'
如果你想包含当前目录,使用-exec会更简单:
find . -type d -exec sh -c 'cd -P -- "{}" && pwd -P' \;
或使用xargs:
find . -type d -print0 | xargs -0 -L1 sh -c 'cd "$0" && pwd && echo Do stuff'
或@gniourf_gniourf建议的类似示例:
find . -type d -print0 | while IFS= read -r -d '' file; do
# ...
done
以上示例支持名称中带有空格的目录。
或者通过分配到 bash 数组中:
dirs=($(find . -type d))
for dir in "${dirs[@]}"; do
cd "$dir"
echo $PWD
done
将. 更改为您的特定文件夹名称。如果您不需要递归运行,则可以使用:dirs=(*)。上面的示例不支持名称中带有空格的目录。
因此,正如@gniourf_gniourf 所建议的那样,在不使用显式循环的情况下将 find 的输出放入数组中的唯一正确方法将在 Bash 4.4 中提供:
mapfile -t -d '' dirs < <(find . -type d -print0)
或者不推荐的方式(涉及parsing of ls):
ls -d */ | awk '{print $NF}' | xargs -n1 sh -c 'cd $0 && pwd && echo Do stuff'
上面的例子会忽略当前的目录(根据 OP 的要求),但它会用空格中断名称。
另见: