首页 > 解决方案 > 循环遍历文件路径以检查目录是否存在

问题描述

我想创建一个 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 命令才能执行此操作?

标签: linuxbashshelldirectory

解决方案


你快到了。

/这个想法是通过在分隔符上拆分目录路径元素来迭代它们。

#!/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

推荐阅读