if [ -d "$DIRECTORY" ]; then echo"$DIRECTORY does exist." fi
检查目录是否不存在
使用! -d选项结合if语句来检查目录是否不存在。示例代码如下:
1 2 3
if [ ! -d "$DIRECTORY" ]; then echo"$DIRECTORY does not exist." fi
处理符号链接
如果后续命令期望操作的是实际目录,而不是符号链接,需要额外处理符号链接。示例代码如下:
1 2 3 4 5 6 7 8 9 10 11
if [ -d "$LINK_OR_DIR" ]; then if [ -L "$LINK_OR_DIR" ]; then # It is a symlink! # Symbolic link specific commands go here. rm"$LINK_OR_DIR" else # It's a directory! # Directory command goes here. rmdir"$LINK_OR_DIR" fi fi
核心代码
短形式检查
1 2
# if $DIR is a directory, then print yes [ -d "$DIR" ] && echo"Yes"
结合find命令检查
1 2 3 4 5 6 7 8 9 10 11 12
# 检查子目录中是否存在指定文件夹 found=`find -type d -name "myDirectory"` if [ -n "$found" ]; then # The variable 'found' contains the full path where "myDirectory" is. # It may contain several lines if there are several folders named "myDirectory". fi
# 检查当前目录中是否存在符合模式的文件夹 found=`find -maxdepth 1 -type d -name "my*"` if [ -n "$found" ]; then # The variable 'found' contains the full path where folders "my*" have been found. fi
检查目录存在并可写
1 2 3
if [ -d "$Directory" -a -w "$Directory" ]; then #Statements fi
检查目录存在,不存在则创建
1
[ -d "$DIRECTORY" ] || mkdir$DIRECTORY
最佳实践
使用双引号包裹变量:当变量包含空格或其他特殊字符时,使用双引号可以避免脚本出错。例如:
1 2 3
if [ -d "$DIRECTORY" ]; then # Will enter here if $DIRECTORY exists, even if it contains spaces fi