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


当前回答

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

其他回答

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

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

较短形式:

# if $DIR is a directory, then print yes
[ -d "$DIR" ] && echo "Yes"

从脚本文件myScript.sh:

if [ -d /home/ec2-user/apache-tomcat-8.5.5/webapps/Gene\ Directory ]; then
   echo "Directory exists!"
   echo "Great"
fi

Or

if [ -d '/home/ec2-user/apache-tomcat-8.5.5/webapps/Gene Directory' ]; then
   echo "Directory exists!"
   echo "Great"
fi

一个衬垫:

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

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

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