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


当前回答

可以使用以下发现,

find . -type d -name dirname -prune -print

其他回答

要检查目录是否存在,可以使用简单的if结构,如下所示:

if [ -d directory/path to a directory ] ; then
# Things to do

else #if needed #also: elif [new condition]
# Things to do
fi

你也可以用否定的方式:

if [ ! -d directory/path to a directory ] ; then
# Things to do when not an existing directory

注意:小心。在开口大括号和闭合大括号的两侧留出空白。

使用相同的语法,您可以使用:

-e: any kind of archive

-f: file

-h: symbolic link

-r: readable file

-w: writable file

-x: executable file

-s: file size greater than zero

如果要检查目录是否存在,无论它是真实目录还是符号链接,请使用以下命令:

ls $DIR
if [ $? != 0 ]; then
        echo "Directory $DIR already exists!"
        exit 1;
fi
echo "Directory $DIR does not exist..."

解释:如果目录或符号链接不存在,则“ls”命令会给出错误“ls:/x:No such file or directory”,并将返回代码设置为非空(通常为“1”),您可以通过“$?”检索该代码。请确保在调用“ls”后直接检查返回代码。

在三元形式中,

[ -d "$directory" ] && echo "exist" || echo "not exist"

通过测试:

test -d "$directory" && echo "exist" || echo "not exist"

使用文件程序。考虑到所有目录也是Linux中的文件,发出以下命令就足够了:

文件$directory_name

检查不存在的文件:文件blah

输出:无法打开“blah”(没有这样的文件或目录)

检查现有目录:文件bluh

输出:bluh:目录

一个衬垫:

[[ -d $Directory ]] && echo true