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


当前回答

在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;

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

要检查多个目录,请使用以下代码:

if [ -d "$DIRECTORY1" ] && [ -d "$DIRECTORY2" ] then
    # Things to do
fi

较短形式:

# if $DIR is a directory, then print yes
[ -d "$DIR" ] && echo "Yes"

测试目录或文件是否存在的简单脚本: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”:文件存在