Command not found in Bash's IF-ELSE condition when using [! -d “$DIR”]

前端 未结 3 1137
感动是毒
感动是毒 2020-12-20 15:39

I have a code like this

#!/bin/bash 
DIR=\"test_dir/\";
if [! -d \"$DIR\"]; then
    # If it doesn\'t create it
    mkdir $DIR
fi

But why

相关标签:
3条回答
  • 2020-12-20 15:51

    Add some spaces:

    if [ ! -d "$DIR" ]; then
    #   ^           ^
    
    0 讨论(0)
  • 2020-12-20 15:56

    Add space between [ and !. And before ] as well.

    #!/bin/bash 
    DIR="test_dir/";
    if [ ! -d "$DIR" ]; then
        # If it doesn't create it
        mkdir $DIR
    fi
    

    It's also a good idea to quote your variable:

        mkdir "$DIR"
    
    0 讨论(0)
  • 2020-12-20 16:08

    You could also attempt to simply by saying:

    test -d "${dir}" || mkdir "${dir}"
    

    This would create the directory if it doesn't exist.

    0 讨论(0)
提交回复
热议问题