什么命令检查Bash shell脚本中是否存在目录?


当前回答

检查目录是否存在,否则创建一个:

[ -d "$DIRECTORY" ] || mkdir $DIRECTORY

其他回答

if [ -d "$DIRECTORY" ]; then
    # Will enter here if $DIRECTORY exists
fi

这不是完全正确的。。。

如果要转到该目录,还需要具有该目录的执行权限。也许你也需要写权限。

因此:

if [ -d "$DIRECTORY" ] && [ -x "$DIRECTORY" ] ; then
    # ... to go to that directory (even if DIRECTORY is a link)
    cd $DIRECTORY
    pwd
fi

if [ -d "$DIRECTORY" ] && [ -w "$DIRECTORY" ] ; then
    # ... to go to that directory and write something there (even if DIRECTORY is a link)
    cd $DIRECTORY
    touch foobar
fi

检查目录是否存在,否则创建一个:

[ -d "$DIRECTORY" ] || mkdir $DIRECTORY

你有没有考虑过只做你想做的事,而不是三思而后行?

也就是说,如果您想在输入目录之前检查其是否存在,请尝试执行以下操作:

if pushd /path/you/want/to/enter; then
    # Commands you want to run in this directory
    popd
fi

如果您给pushd的路径存在,您将输入它,它将以0退出,这意味着将执行语句的then部分。如果它不存在,什么都不会发生(除了一些输出说目录不存在,这可能对调试有帮助的副作用)。

这似乎比这更好,这需要重复自己:

if [ -d /path/you/want/to/enter ]; then
    pushd /path/you/want/to/enter
    # Commands you want to run in this directory
    popd
fi

同样的方法也适用于cd、mv、rm等……如果您在不存在的文件上尝试它们,它们将以错误退出并打印一条消息表示不存在,然后将跳过您的then块。如果您在确实存在的文件上尝试它们,则命令将执行并退出,状态为0,从而允许您的then块执行。

您可以使用test-d(参见man test)。

-d file如果文件存在并且是目录,则为True。

例如:

test -d "/etc" && echo Exists || echo Does not exist

注意:测试命令与条件表达式[(参见:man[)相同,因此它可以跨shell脚本移植。

[-这是测试内置的同义词,但最后一个参数必须是文字],以匹配开头[。

有关可能的选项或进一步帮助,请检查:

帮助[帮助测试人工测试或人工[

实际上,您应该使用几种工具来获得防弹方法:

DIR_PATH=`readlink -f "${the_stuff_you_test}"` # Get rid of symlinks and get abs path
if [[ -d "${DIR_PATH}" ]] ; Then # Now you're testing
    echo "It's a dir";
fi

只要使用“${}”,就不必担心空格和特殊字符。

请注意,[[]]不像[]那样可移植,但由于大多数人都使用现代版本的Bash(毕竟,大多数人甚至不使用命令行:-p),所以好处大于麻烦。