什么命令检查Bash shell脚本中是否存在目录?
当前回答
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
其他回答
使用-e检查将检查文件,其中包括目录。
if [ -e ${FILE_PATH_AND_NAME} ]
then
echo "The file or directory exists."
fi
有很多很好的解决方案,但如果您不在正确的目录中,最终每个脚本都会失败。所以代码如下:
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
只有在执行时,您所在的目录中恰好有一个子目录,您才能成功执行。
我理解这样的初始问题:无论用户在文件系统中的位置如何,都要验证目录是否存在。因此,使用命令“find”可能会奏效:
dir=" "
echo "Input directory name to search for:"
read dir
find $HOME -name $dir -type d
此解决方案很好,因为它允许使用通配符,这是搜索文件/目录时的一个有用功能。唯一的问题是,如果搜索到的目录不存在,“find”命令将不会将任何内容打印到标准输出中(对我来说这不是一个优雅的解决方案),但仍然会有一个零出口。也许有人可以改进一下。
if [ -d "$Directory" -a -w "$Directory" ]
then
#Statements
fi
上述代码检查目录是否存在以及是否可写。
实际上,您应该使用几种工具来获得防弹方法:
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),所以好处大于麻烦。
要检查目录是否存在:
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在另一个答案中解释了这一点的原因。
如果变量包含空格或其他异常字符,则可能会导致脚本失败。