How to mkdir only if a directory does not already exist?
#1
I'm working on a shell script for a project designed to run in the KornShell (ksh) environment on an AIX system. Part of the script's functionality is to create a directory to store output files. However, given the nature of the script, it's possible it might be run multiple times, and I do not want to trigger an error or create multiple instances of this directory if it already exists.
The conventional method for creating a directory is to use `mkdir`, but as mentioned, this will throw a "File exists" error if the directory is already there. I need a way to either check if the directory exists before attempting to create it, or a method to suppress the error and continue with the script execution without halting the process.
I've considered using `if` statements to check the existence of the directory with `test` or `[`, but I wanted to consult the forum to see if there's a more elegant solution or best practice that I might be overlooking. Here is the basic code that I've come up with:

Code:
then
mkdir / my / target / directory
fi

While the above works, I am curious if there's another recommended method to handle this scenario in ksh. Maybe there's a specific flag for `mkdir` that I am not aware of or a one-liner that can accomplish the same result more efficiently. Any insights or examples would be greatly appreciated.
Reply
#2
You can simplify the directory creation process and make your command more idiomatic to ksh by using the `mkdir` command with the `-p` option. This option, which stands for "parents", will create the directory if it does not exist, and will not return an error if it already does. It's a common practice to use this option in scripts to ensure idempotency (the property that a script can be run multiple times without changing the result beyond the initial application).
Here’s how you can use it:


This one-liner is robust and considered good practice when writing scripts where the directory structure may or may not be present already. It eliminates the need for the `if` test and simplifies your code.
Reply
#3
That is a much cleaner approach, indeed. The `-p` flag seems to be exactly what I was looking for. It makes the script more readable and efficient. I will incorporate this into my script. Thank you for your suggestion. Below is the updated code with the improvements:

Code:
#!/bin/ksh

# Ensure the directory exists without reporting an error
if it already does
mkdir - p / my / target / directory
#...additional script logic...

This should maintain the functionality I need while adhering to best practices. I appreciate the concise and helpful response.
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)