检查一个目录是否包含另一个目录

Check if a directory contains another directory

如何检查给定目录是否包含 shell 中的另一个目录。我想传递 2 个完整路径目录。 (我知道这很愚蠢,但仅用于学习目的)。然后我想看看这两条路径中的任何一条是否包含在另一条路径中。

parent=
child=

if [ -d $child ]; then
    echo "YES"
else
    echo "NO"
fi

然而,这并没有使用 parent 目录。只检查 child 是否存在。

您可以使用 find 查看一个名称是否包含在另一个名称中:

result=$(find "$parent" -type d -name "$child")
if [[ -n $result ]]
then echo YES
else echo NO
fi

您完全可以做到这一点 bash。遍历 $1 中的每个文件并查看“$1/$2”是否是目录,如下所示:

parent=
child=$(basename )
if [ -d $parent ] && [ -d $child ]; then
    for child in $parent; do
        if [ -d "$parent/$child" ]; then
            echo "Yes"
        else
            echo "No"
        fi
    done
fi

使用以下代码创建文件(例如:dircontains.sh):

#!/bin/bash

function dircontains_syntax {
    local msg=
    echo "${msg}" >&2
    echo "syntax: dircontains <parent> <file>" >&2
    return 1
}

function dircontains {
    local result=1
    local parent=""
    local parent_pwd=""
    local child=""
    local child_dir=""
    local child_pwd=""
    local curdir="$(pwd)"
    local v_aux=""

    # parameters checking
    if [ $# -ne 2 ]; then
        dircontains_syntax "exactly 2 parameters required"
        return 2
    fi
    parent=""
    child=""

    # exchange to absolute path
    parent="$(readlink -f "${parent}")"
    child="$(readlink -f "${child}")"
    dir_child="${child}"

    # direcory checking
    if [ ! -d "${parent}" ];  then
        dircontains_syntax "parent dir ${parent} not a directory or doesn't exist"
        return 2
    elif [ ! -e "${child}" ];  then
        dircontains_syntax "file ${child} not found"
        return 2
    elif [ ! -d "${child}" ];  then
        dir_child=`dirname "${child}"`
    fi

    # get directories from $(pwd)
    cd "${parent}"
    parent_pwd="$(pwd)"
    cd "${curdir}"  # to avoid errors due relative paths
    cd "${dir_child}"
    child_pwd="$(pwd)"

    # checking if is parent
    [ "${child_pwd:0:${#parent_pwd}}" = "${parent_pwd}" ] && result=0

    # return to current directory
    cd "${curdir}"
    return $result
}    

然后运行这些命令

. dircontains.sh

dircontains path/to/dir/parent any/file/to/test

# the result is in $? var 
# =0, <file> is in <dir_parent>
# =1, <file> is not in <dir_parent>
# =2, error

观测:
- 仅在 ubuntu 16.04/bash
中测试 - 在这种情况下,第二个参数可以是任何 Linux 文件

纯bash,没有使用外部命令:

#!/bin/bash

parent=
child=
[[ $child && $parent ]] || exit 2 # both arguments must be present
child_dir="${child%/*}"           # get the dirname of child
if [[ $child_dir = $parent && -d $child ]]; then
  echo YES
else
  echo NO
fi

适用于以下子目录:

parent=
child=

if [[ ${child/$parent/} != $child ]] ; then
    echo "YES"
else
    echo "NO"
fi

类似于但比名称比较可靠得多:

if find "$parent" -samefile "$child" -printf 'Y\n' -quit | grep -qF Y; then
    echo "contains '$child'"
fi

为了更安全,您还可以遵循符号链接以确保对 $parent 的递归操作不会损坏 $child 或其中的任何内容:

if find -L "$parent" -samefile "$child" -printf 'Y\n' -quit | grep -qF Y; then
    echo "contains '$child' or link thereto"
fi