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

时间:2015-02-05 03:09:19

标签: bash shell unix

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

parent=$1
child=$2

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

然而,这不使用父目录。仅检查孩子是否存在。

5 个答案:

答案 0 :(得分:4)

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

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

答案 1 :(得分:0)

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

#!/bin/bash

function dircontains_syntax {
    local msg=$1
    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="${1}"
    child="${2}"

    # 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 
# $1=0, <file> is in <dir_parent>
# $1=1, <file> is not in <dir_parent>
# $1=2, error

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

答案 2 :(得分:0)

纯bash,不使用外部命令:

#!/bin/bash

parent=$1
child=$2
[[ $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

答案 3 :(得分:0)

也可用于子目录:

parent=$1
child=$2

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

答案 4 :(得分:-1)

你可以用纯粹的bash来完成这个。循环遍历$ 1中的每个文件,看看&#34; $ 1 / $ 2&#34;是一个dir,像这样:

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