Please use
[code][/code] tags around your code and data, to preserve formatting and to improve readability. Please do not use quote tags, colors, or other fancy formatting.
Actually, all of the attempts posted in the OP should work just fine, provided the correct syntax is used (and there are no other file/directory conflicts, as discussed).
Code:
if [ -d "$dir"" ] ; then
:
else
mkdir "$dir"
fi
if ! [ -d "$dir" ]; then
mkdir "$dir"
fi
if [ ! -d "$dir" ]; then
mkdir "$dir"
fi
In the first example, we simply use any sub-command that does nothing on a successful match. The "
true" placeholder command ("
:" is a synonym for it) is usually the recommended option. "
false" can be used as well, but it might have a different effect if any subsequent command depends on reading the exit status of it. Even something like "
echo -n" would do.
The second one works because placing a "
!" in front of any command inverts the success/failure exit status of it. In this case you're reversing the status of the "
test" command.
The third one is probably best though, as "
!" is also the
test command syntax for reversing the status of that individual match.
The important thing about all of them though is to remember that "
test/
[" is a
command, just like any other, and so it's important to include spaces around each argument that comes after it. You also have to quote any variables and command substitutions, so that the expanded value doesn't get split into separate arguments from word-splitting and glob expansion.
See the
Bash Pitfalls for details on common problems like this.
(I believe #4 is the main one, but for some reason the site currently isn't responding for me.)
As mentioned though, when using
bash or
ksh, it's usually recommended to use
[[..]] for string/file tests. Since "
[[" is a shell keyword, not a command, the shell can parse the line more safely, and doesn't do any word-splitting or expansion of variable contents.
In addition, when doing integer comparisons, you should use the
((..)) arithmetic evaluation brackets instead. In either case, avoid using the old
[..] test unless you specifically need POSIX-style portability.
http://mywiki.wooledge.org/ArithmeticExpression
http://mywiki.wooledge.org/BashFAQ/031
http://wiki.bash-hackers.org/commands/classictest
http://wiki.bash-hackers.org/syntax/...nal_expression
And to give one final bit of advice, environment variables are generally all upper-case. So while not absolutely necessary, it's good practice to keep your own user variables in lower-case or mixed-case, to help differentiate them.