【问题标题】:Loop through file path to check if directory exists循环遍历文件路径以检查目录是否存在
【发布时间】:2021-02-20 22:56:21
【问题描述】:

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

【问题讨论】:

    标签: linux bash shell directory


    【解决方案1】:

    你快到了。

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

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

    【讨论】:

      【解决方案2】:

      我不知道它是否会帮助你,但你可以使用 Python,因为你必须在 linux 中运行命令,它必须安装 Python,在 python 中列出文件或文件夹很简单:

      import os
      
      DIR = "/etc/example/httpd/"
      files = os.listdir(DIR) #Returns a list of files/folders from that directory
      

      【讨论】:

      • 是否可以在此使用 bash linux 脚本?
      • 没有理由为此引入 Python。检查目录完全是在 Bash 的驾驶室中。照原样,您能否提供执行 OP 所需的 Python 代码? os.listdir 不这样做。
      猜你喜欢
      • 2016-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-26
      • 2020-08-09
      • 1970-01-01
      • 2019-08-05
      • 1970-01-01
      相关资源
      最近更新 更多