12

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
  • 5
    The name [ is the name of a command, not random punctuation. Just as you need a space between cat and /etc/passwd in cat/etc/passwd, so you need a space between [ (the command name) and ! (one of its arguments). Similarly, the last argument must be ]. This requirement goes back to ancient history (7th Edition UNIX™ circa 1978, or earlier) when the shell did not have a test (aka [) built-in and the only test command was /bin/test and its (hard) link /bin/[. Commented Aug 8, 2013 at 7:08

3 Answers 3

34

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"
Sign up to request clarification or add additional context in comments.

Comments

11

Add some spaces:

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

Comments

1

You could also attempt to simply by saying:

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

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

2 Comments

Or, even easier: mkdir -p "$DIR" (using the upper-case name as in the question). This creates all directories needed on the path, but succeeds if the directory already exists.
@JonathanLeffler Yup, mkdir -p foo by itself doesn't do any harm.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.