How to: Make a directory structure in Ubuntu only if the directories do not exist
Lately I have been working on start up scripts but because I use temporary storage for some mounts the information contained within them is cleared with each reboot (shutdown / turn on – Windows Azure). This means that the folder structure I created gets lost with the rest of the files. This is fine except for the fact that the application does not create the directories if they do not exist and that means it fails to properly load.I guess you can see where I am going with this: I need a way to success create an entire directory structure regardless of which folders do or not exist.
I did some research and found a great way to achieve this using our already familiar mkdir command. There is an argument you can use:
-p, --parents no error if existing, make parent directories as needed
As I mentioned, I needed a way to create an entire directory structure. Using the -p or –parents arguments you are indicating exactly that: Create all parent directories as needed (so, if they already exist it will skip them). Traditionally you would use mkdir like this: mkdir /etc/myapp and then mkdir /etc/myapp/mydir and then mkdir /etc/myapp/mydir/mysubdir and so on. /etc/ already comes by default with your ubuntu system but if you wanted to create the /etc/myapp/mydir/mysubdir in one sweep move you could use: mkdir -p /etc/myapp/mydir/mysubdir. The benefit here is that no matter how many of those directories do or not exist, the system will create the ones missing. So assuming you already had /etc/myapp it will create the mydir and the mysubdir directories only. This is a great thing to know. I usually try to create them all at once and then the system would complaint the path does not exist so I had to go creating one directory at a time. I just recently started using Ubuntu so perhaps that was a rookie thing to do but discovering the –parents argument really helps a lot. This was particularly true when using the scripts as trying to create a directory that already exists throws an error, while using the parents argument because it only makes directories as needed you don’t get error messages when the parents already exists.
Another important thing to keep in mind is that you could add validation to decide whether you need to create or not the folder. Validation could also account to check if by accident a file was created instead of a folder at the end of the directory structure. Take the following code for example:
What this code is the following:
- If the specified directory ($dir) does not exist then:
- Make the directory structure using the –parent argument we just discussed
- If the specified route ($dir) does exist then check if it is a directory. If the route is not a directory then:
- Display a message indicating that the specified route ($dir) is not a directory