什么命令检查Bash shell脚本中是否存在目录?
当前回答
较短形式:
# if $DIR is a directory, then print yes
[ -d "$DIR" ] && echo "Yes"
其他回答
在Bash脚本中引用变量时,始终将变量括在双引号中。
if [ -d "$DIRECTORY" ]; then
# Will enter here if $DIRECTORY exists, even if it contains spaces
fi
现在的孩子们在他们的目录名中添加空格和许多其他有趣的字符。(空间!在我的时代,我们没有花哨的空间!)有一天,这些孩子中的一个会运行你的脚本,$DIRECTORY设置为“My M0viez”,你的脚本就会崩溃。你不想这样。所以使用双引号。
file="foo"
if [[ -e "$file" ]]; then echo "File Exists"; fi;
(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:找不到[没有这样的文件或目录]
要检查目录是否存在,可以使用简单的if结构,如下所示:
if [ -d directory/path to a directory ] ; then
# Things to do
else #if needed #also: elif [new condition]
# Things to do
fi
你也可以用否定的方式:
if [ ! -d directory/path to a directory ] ; then
# Things to do when not an existing directory
注意:小心。在开口大括号和闭合大括号的两侧留出空白。
使用相同的语法,您可以使用:
-e: any kind of archive
-f: file
-h: symbolic link
-r: readable file
-w: writable file
-x: executable file
-s: file size greater than zero
如果要检查目录是否存在,无论它是真实目录还是符号链接,请使用以下命令:
ls $DIR
if [ $? != 0 ]; then
echo "Directory $DIR already exists!"
exit 1;
fi
echo "Directory $DIR does not exist..."
解释:如果目录或符号链接不存在,则“ls”命令会给出错误“ls:/x:No such file or directory”,并将返回代码设置为非空(通常为“1”),您可以通过“$?”检索该代码。请确保在调用“ls”后直接检查返回代码。