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


当前回答

可以使用以下发现,

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

其他回答

可以使用以下发现,

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

作为“[-d]”和“[-h]”选项的替代,您可以使用stat获取文件类型并对其进行分析。

#! /bin/bash
MY_DIR=$1
NODE_TYPE=$(stat -c '%F' ${MY_DIR} 2>/dev/null)
case "${NODE_TYPE}" in
        "directory") echo $MY_DIR;;
    "symbolic link") echo $(readlink $MY_DIR);;
                 "") echo "$MY_DIR does not exist";;
                  *) echo "$NODE_TYPE is unsupported";;
esac
exit 0

测试数据:

$ mkdir tmp
$ ln -s tmp derp
$ touch a.txt
$ ./dir.sh tmp
tmp
$ ./dir.sh derp
tmp
$ ./dir.sh a.txt
regular file is unsupported
$ ./dir.sh god
god does not exist

要检查目录是否存在,可以使用简单的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

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

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

例如:

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

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

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

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

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

使用-e检查将检查文件,其中包括目录。

if [ -e ${FILE_PATH_AND_NAME} ]
then
    echo "The file or directory exists."
fi