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?
You could also attempt to simply by saying:
test -d "${dir}" || mkdir "${dir}"
This would create the directory if it doesn't exist.
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.mkdir -p foo by itself doesn't do any harm.
[is the name of a command, not random punctuation. Just as you need a space betweencatand/etc/passwdincat/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 atest(aka[) built-in and the onlytestcommand was/bin/testand its (hard) link/bin/[.