什么命令检查Bash shell脚本中是否存在目录?
当前回答
可以使用以下发现,
find . -type d -name dirname -prune -print
其他回答
有很多很好的解决方案,但如果您不在正确的目录中,最终每个脚本都会失败。所以代码如下:
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”命令将不会将任何内容打印到标准输出中(对我来说这不是一个优雅的解决方案),但仍然会有一个零出口。也许有人可以改进一下。
(1)
[ -d Piyush_Drv1 ] && echo ""Exists"" || echo "Not Exists"
(2)
[ `find . -type d -name Piyush_Drv1 -print | wc -l` -eq 1 ] && echo Exists || echo "Not Exists"
(3)
[[ -d run_dir && ! -L run_dir ]] && echo Exists || echo "Not Exists"
如果发现上述方法之一存在问题:
使用ls命令;目录不存在的情况-显示错误消息
[[ `ls -ld SAMPLE_DIR| grep ^d | wc -l` -eq 1 ]] && echo exists || not exists
-ksh:not:找不到[没有这样的文件或目录]
[ -d ~/Desktop/TEMPORAL/ ] && echo "DIRECTORY EXISTS" || echo "DIRECTORY DOES NOT EXIST"
这个答案被包装成一个shell脚本
示例
$ is_dir ~
YES
$ is_dir /tmp
YES
$ is_dir ~/bin
YES
$ mkdir '/tmp/test me'
$ is_dir '/tmp/test me'
YES
$ is_dir /asdf/asdf
NO
# Example of calling it in another script
DIR=~/mydata
if [ $(is_dir $DIR) == "NO" ]
then
echo "Folder doesnt exist: $DIR";
exit;
fi
is目录
function show_help()
{
IT=$(CAT <<EOF
usage: DIR
output: YES or NO, depending on whether or not the directory exists.
)
echo "$IT"
exit
}
if [ "$1" == "help" ]
then
show_help
fi
if [ -z "$1" ]
then
show_help
fi
DIR=$1
if [ -d $DIR ]; then
echo "YES";
exit;
fi
echo "NO";
注意-d测试可能会产生一些令人惊讶的结果:
$ ln -s tmp/ t
$ if [ -d t ]; then rmdir t; fi
rmdir: directory "t": Path component not a directory
下面的文件:“什么时候目录不是目录?”答案:“当它是指向目录的符号链接时。”
if [ -d t ]; then
if [ -L t ]; then
rm t
else
rmdir t
fi
fi
您可以在Bash手册中找到有关Bash条件表达式、内置命令和[[复合命令的更多信息。