循环遍历文件路径以检查目录是否存在

约翰尼·林

我想创建一个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命令才能做到这一点?

莉亚·格雷(Lea Gray)

你快到了。

这个想法是通过在/定界符上分割目录路径元素来迭代它们

#!/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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

Python:检查指定路径下是否存在非目录文件

循环检查目录是否存在

递归检查路径中的目录是否存在

bash for 循环检查目录是否存在

如何在php中检查远程路径上是否存在文件夹或目录

在目录外运行脚本时使用路径检查文件是否存在

检查文件路径列表是否存在

测试路径,检查文件是否存在

检查文件是否存在于路径中的任何目录中或当前目录是否在 git 项目中

检查Java目录中是否存在文件

如何检查文件或目录是否存在?

检查目录中是否存在文件

如何使用while循环检查目录中是否存在两个文件?

如何根据路径java检查目录是否存在

Shell脚本检查dir目录是否存在然后更改路径,如果不存在则使用该名称创建dir并检查文件名不存在

Bash 脚本循环遍历所有子目录,检查脚本目录是否存在,并在那里运行脚本

如何检查bash中是否存在文件或文件目录?

如何检查文件目录中是否存在多个文件?(迅速)

检查路径上的对象是否是跨平台的文件或目录?

PoshRSJob 循环遍历文件目录

循环遍历目录中的文件

加入路径以检查文件是否存在时出错

检查列表中是否存在多个文件(不同的路径)

Bash +检查文件是否存在并带有路径〜

如何检查Scala中是否存在路径或文件

检查文件在Rails公用路径中是否存在

tcsh检查给定路径中是否存在文件

需要检查目录中是否存在.gz文件

如何使用Deno检查文件或目录是否存在?