什么命令检查Bash shell脚本中是否存在目录?


当前回答

测试目录或文件是否存在的简单脚本:if[-d/home/ram/dir]#对于文件“if[-f/home/rama/file]”然后echo“目录存在”其他的echo“目录不存在”传真检查目录是否存在的简单脚本:mkdir tempdir#如果要检查文件,请使用touch而不是mkdirret=$?如果[“$ret”==“0”]然后echo“目录存在”其他的echo“目录不存在”传真以上脚本将检查目录是否存在$? 如果最后一个命令成功,则返回“0”,否则返回非零值。假设tempdir已经存在。然后mkdir tempdir将给出如下错误:mkdir:无法创建目录“tempdir”:文件存在

其他回答

if [ -d "$Directory" -a -w "$Directory" ]
then
    #Statements
fi

上述代码检查目录是否存在以及是否可写。

在Bash脚本中引用变量时,始终将变量括在双引号中。

if [ -d "$DIRECTORY" ]; then
    # Will enter here if $DIRECTORY exists, even if it contains spaces
fi

现在的孩子们在他们的目录名中添加空格和许多其他有趣的字符。(空间!在我的时代,我们没有花哨的空间!)有一天,这些孩子中的一个会运行你的脚本,$DIRECTORY设置为“My M0viez”,你的脚本就会崩溃。你不想这样。所以使用双引号。

使用-e检查将检查文件,其中包括目录。

if [ -e ${FILE_PATH_AND_NAME} ]
then
    echo "The file or directory exists."
fi
[[ -d "$DIR" && ! -L "$DIR" ]] && echo "It's a directory and not a symbolic link"

注:引用变量是一种很好的做法。

说明:

-d: 检查是否是目录-五十: 检查是否是符号链接

要检查目录是否存在,可以使用简单的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