我想创建一个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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句