什么命令检查Bash shell脚本中是否存在目录?
当前回答
[[ -d "$DIR" && ! -L "$DIR" ]] && echo "It's a directory and not a symbolic link"
注:引用变量是一种很好的做法。
说明:
-d: 检查是否是目录-五十: 检查是否是符号链接
其他回答
较短形式:
# if $DIR is a directory, then print yes
[ -d "$DIR" ] && echo "Yes"
有很多很好的解决方案,但如果您不在正确的目录中,最终每个脚本都会失败。所以代码如下:
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”命令将不会将任何内容打印到标准输出中(对我来说这不是一个优雅的解决方案),但仍然会有一个零出口。也许有人可以改进一下。
在三元形式中,
[ -d "$directory" ] && echo "exist" || echo "not exist"
通过测试:
test -d "$directory" && echo "exist" || echo "not exist"
if [ -d "$DIRECTORY" ]; then
# Will enter here if $DIRECTORY exists
fi
这不是完全正确的。。。
如果要转到该目录,还需要具有该目录的执行权限。也许你也需要写权限。
因此:
if [ -d "$DIRECTORY" ] && [ -x "$DIRECTORY" ] ; then
# ... to go to that directory (even if DIRECTORY is a link)
cd $DIRECTORY
pwd
fi
if [ -d "$DIRECTORY" ] && [ -w "$DIRECTORY" ] ; then
# ... to go to that directory and write something there (even if DIRECTORY is a link)
cd $DIRECTORY
touch foobar
fi
使用-e检查将检查文件,其中包括目录。
if [ -e ${FILE_PATH_AND_NAME} ]
then
echo "The file or directory exists."
fi