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


当前回答

file="foo" 
if [[ -e "$file" ]]; then echo "File Exists"; fi;

其他回答

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

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

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

文件$directory_name

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

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

检查现有目录:文件bluh

输出:bluh:目录

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

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),所以好处大于麻烦。

作为“[-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
[ -d ~/Desktop/TEMPORAL/ ] && echo "DIRECTORY EXISTS" || echo "DIRECTORY DOES NOT EXIST"