如何确保两个目录不是彼此的子目录(BASH)

时间:2011-07-13 20:46:17

标签: bash subdirectory

编辑:这或多或少是我在@ Mechanical的良好输入后出现的。有什么见解吗?

#!/bin/bash

path1="$(readlink -e "$1")"
path2="$(readlink -e "$2")"

EBADARGS=65

function checkArgsNumber()
{
    if test "$#" -ne 2; then
        echo "ERRORE: this script takes exactly 2 params."  
        exit $EBADARGS
    fi
}

function checkExistence()
{
    if [ ! -d $path1 ]; then
        echo  "ERROR: "$1" does not exist"
        exit $EBADARGS
    elif [ ! -d "$2" ]; then
        echo  "ERROR: "$2" does not exist"
        exit $EBADARGS
    elif [[ -L $path1 ]]; then
        echo "ERROR: path1 can't be a symbolic link"
        exit $EBADARGS
    elif [[ -L $2 ]]; then
        echo "ERROR: path2 can't be a symbolic  link"
        exit $EBADARGS
    fi
}

function checkIfSame()
{
    if [[ $path1 == $path2 ]]; then
        echo "ERROR: path1 and path2 must be different directories"
        exit $EBADARGS     
    fi   
}

function checkIfSubdirectories()
{
    if [[ $path1 = *$path2* ]]; then
        echo "ERROR:"$1" is a $path2 subdirectory"
        exit $EBADARGS
    elif [[ $path2 = *$path1* ]]; then
        echo "ERROR:"$2" is a  $path1 subdirectory"
        exit $EBADARGS
    elif [[ -e "$(find $path1 -samefile $path2)" ]]; then
        echo "ERROR:"$(find $path1 -samefile $path2 -print0)" and "$2" have the same inode, $path2 is a  $path1 subdirectory"
        exit $EBADARGS
    elif [[ -e "$(find $path2 -samefile $path1)" ]]; then
        echo "ERROR:"$(find $path2 -samefile $path1 -print0)" and "$2" have the same inode,  $path1 is a  $path2 subdirectory"
        exit $EBADARGS
    fi
}

checkArgsNumber "$@"
checkExistence "$@"
checkIfSame "$@"
checkIfSubdirectories "$@"

现在..这应该有用,我希望它在某种程度上有用。 有人可以解释一下*$path2*部分是如何工作的吗?这个* *运算符的名称是什么?我应该去哪里阅读它?

1 个答案:

答案 0 :(得分:2)

一些问题:

文体

您应该引用整个参数来回显,如

    echo "ERROR: $1 is a subdirectory of $(readlink -e "$2")"

如果没有echo参数的引号,你在技术上将每个单词作为自己的参数传递:echo "ERROR:somedir" "is" "a" "subdirectory" ....由于echo按照给定的顺序打印其参数,用空格分隔,输出在你的情况下是相同的。但从语义上讲,这不是你想要的。

(一个不同的例子:

echo foo          bar

会打印foo bar。)

错误消息无法正常工作

如果参数不存在

$ ./check.sh nonexistent1 nonexistent2
ERROR:nonexistent1 is a subdirectory of 

显然,如果您已经检查过它们,那就无关紧要了。

您同样需要检查角落情况,例如参数引用同一目录的位置:

$ mkdir a b
$ ln -s ../a b/c
$ ./check.sh a b/c
ERROR:a is a subdirectory of /dev/shm/a

未检测到符号链接

$ mkdir a b
$ ln -s ../a b/c
$ ./check.sh a b

没有给出任何错误消息。

未检测到mount --bind

$ mkdir a b b/c
$ sudo mount --bind a b/c
$ ./check.sh a b

没有给出任何错误消息。