什么命令检查Bash shell脚本中是否存在目录?
当前回答
要检查目录是否存在:
if [ -d "$DIRECTORY" ]; then
echo "$DIRECTORY does exist."
fi
要检查目录是否不存在:
if [ ! -d "$DIRECTORY" ]; then
echo "$DIRECTORY does not exist."
fi
然而,正如JonEricson指出的,如果不考虑到指向目录的符号链接也会通过此检查,则后续命令可能无法按预期工作。例如,执行以下操作:
ln -s "$ACTUAL_DIR" "$SYMLINK"
if [ -d "$SYMLINK" ]; then
rmdir "$SYMLINK"
fi
将生成错误消息:
rmdir: failed to remove `symlink': Not a directory
因此,如果后续命令需要目录,则可能需要对符号链接进行不同的处理:
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
特别注意用于包装变量的双引号。8jean在另一个答案中解释了这一点的原因。
如果变量包含空格或其他异常字符,则可能会导致脚本失败。
其他回答
ls命令与-l(长列表)选项一起返回有关文件和目录的属性信息。特别是ls-l输出的第一个字符通常是d或a-(破折号)。在d的情况下,列出的是一个目录。
仅一行中的以下命令将告诉您给定的ISDIR变量是否包含指向目录的路径:
[[ $(ls -ld "$ISDIR" | cut -c1) == 'd' ]] &&
echo "YES, $ISDIR is a directory." ||
echo "Sorry, $ISDIR is not a directory"
实际用途:
[claudio@nowhere ~]$ ISDIR="$HOME/Music"
[claudio@nowhere ~]$ ls -ld "$ISDIR"
drwxr-xr-x. 2 claudio claudio 4096 Aug 23 00:02 /home/claudio/Music
[claudio@nowhere ~]$ [[ $(ls -ld "$ISDIR" | cut -c1) == 'd' ]] &&
echo "YES, $ISDIR is a directory." ||
echo "Sorry, $ISDIR is not a directory"
YES, /home/claudio/Music is a directory.
[claudio@nowhere ~]$ touch "empty file.txt"
[claudio@nowhere ~]$ ISDIR="$HOME/empty file.txt"
[claudio@nowhere ~]$ [[ $(ls -ld "$ISDIR" | cut -c1) == 'd' ]] &&
echo "YES, $ISDIR is a directory." ||
echo "Sorry, $ISDIR is not a directoy"
Sorry, /home/claudio/empty file.txt is not a directory
使用文件程序。考虑到所有目录也是Linux中的文件,发出以下命令就足够了:
文件$directory_name
检查不存在的文件:文件blah
输出:无法打开“blah”(没有这样的文件或目录)
检查现有目录:文件bluh
输出:bluh:目录
较短形式:
# if $DIR is a directory, then print yes
[ -d "$DIR" ] && echo "Yes"
作为“[-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
使用-e检查将检查文件,其中包括目录。
if [ -e ${FILE_PATH_AND_NAME} ]
then
echo "The file or directory exists."
fi