linux - 循环遍历文件路径以检查目录是否存在
问题描述
我想创建一个 linux bash 脚本来循环遍历目录路径以检查每个目录是否存在。这只是一个简单的例子,
DIR="/etc/example/httpd/"
if [ -d "$DIR" ]; then
echo "$dir exists"
else
echo "$dir does not exists"
fi
我想回显目录的输出
/etc exists
/etc/example does not exists
/etc/example/httpd does not exists
这是否意味着我必须执行很多 cd 命令才能执行此操作?
解决方案
你快到了。
/
这个想法是通过在分隔符上拆分目录路径元素来迭代它们。
#!/usr/bin/env bash
DIR="/etc/example/httpd"
dir=
# While there is a path element delimited by / to read
# or the element is not empty (but not followed by a trailing /)
while read -r -d/ e || [ -n "$e" ]; do
# If the element is not empty
if [ -n "$e" ]; then
# Postfix the element to the dir path with /
dir+="/$e"
if [ -d "$dir" ]; then
echo "$dir exists"
else
echo "$dir does not exists"
fi
fi
done <<<"$DIR"
替代方法:
#!/usr/bin/env bash
DIR="/etc/example/httpd/"
# Set the Internal Field Separator to /
IFS=/
# Map the DIR path elements into an array arr
read -r -a arr <<<"$DIR"
# Starting at element 1 (skip element 0) and up to number of entries
for ((i=1; i<${#arr[@]}; i++)); do
# Combine dir path from element 1 to element i of the array
dir="/${arr[*]:1:i}"
if [ -d "$dir" ]; then
echo "$dir exists"
else
echo "$dir does not exists"
fi
done
最后是一个 POSIX shell 语法方法:
#!/usr/bin/env sh
DIR="/etc/example/httpd/"
dir=
IFS=/
# Iterate DIR path elmeents delimited by IFS /
for e in $DIR; do
# If path element is not empty
if [ -n "$e" ]; then
# Append the element to the dir path with /
dir="$dir/$e"
if [ -d "$dir" ]; then
echo "$dir exists"
else
echo "$dir does not exists"
fi
fi
done
exit
推荐阅读
- angularjs - 有没有办法使用 Angular Element 将 AngularJS 组件包装到 Web 组件中?
- python - 多线程下载器无故变慢
- android - 带有recycleview的左滑动布局
- javascript - 如何在 JavaScript 中使用变量跟踪值,而不在递归调用中重置所述变量,而不使用全局变量?
- python - 如何创建 lambda 的 python 列表理解?
- python - 使用 ElementTree 解析 XML 中的 if-else 查找
- python - 尝试向 Seaborn 散点图添加颜色条
- android - 如何同时实现(视频录制和实时抓帧)?
- amazon-web-services - 即使 Nginx 配置更新,带有 Amazing Linux 2 的 ElasticBeanstalk 也会持续超时
- javascript - Node-Scheduler JavaScript 循环其工作