Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

16
  • 46
    If you want to play it safe with the GNU tools, use of -- is highly recommended (end-of-options marker). Otherwise, if your variable contains something that looks like an option, the script'll fail just as with spaces. Commented Jul 21, 2009 at 16:36
  • 4
    For modern versions of bash, ksh, etc. [...] is a builtin Commented Mar 24, 2011 at 14:22
  • 99
    One thing to keep in mind: [ ! -d "$DIRECTORY" ] will be true either if $DIRECTORY doesn't exist, or if does exist but isn't a directory. Consider something like if [ ! -d "$DIRECTORY" ] ; then mkdir "$DIRECTORY" ; fi; this will fail if "$DIRECTORY" is a file. (Of course you should check whether mkdir succeeded anyway; there are a number of reasons it can fail.) Commented Aug 9, 2011 at 23:46
  • 11
    It might be worth mentioning that as soon as the check has been performed the situation can have changed already due to other processes. In many cases it is better to just create or use the directory and react on a failure. Commented Sep 9, 2013 at 11:51
  • 22
    Instead of testing for both the directory (-d) and the symlink (-L), it's easier just to append a slash to the variable, like if [ -d "${THING:+$THING/}" ]. A directory won't mind the extra slash. A file will evaluate to false. Empty will remain empty, so false. And a symlink will be resolved to its destination. Of course, it depends on your goal. If you want to go there, this is fine. If you want to delete it, then the code in this answer is better. Commented Jan 17, 2017 at 9:21