簡體   English   中英

循環遍歷文件路徑以檢查目錄是否存在

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

我想創建一個 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

我不知道它是否會幫助你,但你可以使用 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