Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 376
neversaint Avatar asked Aug 08 '13 06:08

neversaint


1 Answers

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"
like image 195
konsolebox Avatar answered Sep 20 '22 03:09

konsolebox