I am trying to create a script to detect whether a directory exists, and if it does not, to create it.
How can I do that?
I did some digging and found a clue:
test -d directory
…will return true or false depending on whether the directory exists or not.
But how do I tie this together with mkdir?
mkdir -p $directoryshould do what you want. The-poption will create any necessary parent directories. If$directoryalready exists as a directory, the command does nothing, and succeeds. If$directoryis a regular file, it will remain untouched, and the command will fail with an appropriate error message.Without the
-poption tomkdir, thetest ... || mkdir ...strategy can fail if$directorycontains a ‘/’, and some component of that path doesn’t already exist. Thetestis superfluous anyway, sincemkdirdoes the same test internally.