在Bash shell脚本中检查目录是否存在的方法

在Bash shell脚本中检查目录是否存在的方法

技术背景

在Bash shell脚本编程中,经常需要检查某个目录是否存在,以便根据检查结果执行不同的操作,如创建目录、进入目录等。了解如何正确检查目录的存在性是编写健壮脚本的基础。

实现步骤

检查目录是否存在

使用-d选项结合if语句来检查目录是否存在。示例代码如下:

1
2
3
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
  • 使用readlink -f获取绝对路径:可以消除符号链接的影响,确保检查的是实际的目录。示例代码如下:
1
2
3
4
DIR_PATH=`readlink -f "${the_stuff_you_test}"` # Get rid of symlinks and get abs path
if [[ -d "${DIR_PATH}" ]]; then
echo "It's a dir";
fi
  • 使用pushdpopd:在进入目录前,可以直接使用pushd命令,避免重复检查目录是否存在。示例代码如下:
1
2
3
4
if pushd /path/you/want/to/enter; then
# Commands you want to run in this directory
popd
fi

常见问题

符号链接误判

使用-d检查时,符号链接到目录也会被判定为目录存在。可以结合-L选项来区分目录和符号链接。

变量未正确引用

如果变量未使用双引号包裹,当变量包含空格或特殊字符时,脚本可能会出错。因此,在引用变量时,始终使用双引号。

兼容性问题

[[ ]]结构在现代Bash版本中可用,但不如[ ]结构便携。如果需要兼容旧版本的Bash,建议使用[ ]结构。


在Bash shell脚本中检查目录是否存在的方法
https://119291.xyz/posts/2025-05-09.check-directory-existence-in-bash/
作者
ww
发布于
2025年5月9日
许可协议