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

左心房为你撑大大i 提交于 2019-12-19 17:17:11

问题


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 executing it gave me this:

./mycode.sh: line 16: [!: command not found

What's the right way to do it?


回答1:


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"



回答2:


Add some spaces:

if [ ! -d "$DIR" ]; then
#   ^           ^



回答3:


You could also attempt to simply by saying:

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

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



来源:https://stackoverflow.com/questions/18119689/command-not-found-in-bashs-if-else-condition-when-using-d-dir

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!