简体   繁体   English

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

[英]Loop through file path to check if directory exists

I want to create a linux bash script to loop through the directory path to check if every directory does exists.我想创建一个 linux bash 脚本来循环遍历目录路径以检查每个目录是否确实存在。 This is just a simple example,这只是一个简单的例子,

DIR="/etc/example/httpd/"
if [ -d "$DIR" ]; then
  echo "$dir exists"
else
  echo "$dir does not exists"
fi

I want to echo the output that the directory我想回显目录的输出

/etc exists
/etc/example does not exists
/etc/example/httpd does not exists

Does it mean I have to perform a lot of cd commands in order to do this?这是否意味着我必须执行很多 cd 命令才能做到这一点?

You are almost there.你快到了。

The idea is to iterate the directory path elements by splitting them on the / delimiter.这个想法是通过在/分隔符上拆分它们来迭代目录路径元素。

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

Alternate method:替代方法:

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

And finally a POSIX shell grammar method:最后是一个 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

I don't know if it will help you, but you can use Python, since you must be running the command in linux, it must have Python installed, to make a listing of files or folders in python is simple:我不知道它是否会帮助你,但你可以使用 Python,因为你必须在 linux 中运行命令,它必须安装 Python,在 python 中列出文件或文件夹很简单:

import os

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM