How to mkdir only if a directory does not already exist?
#1
I am currently working on a shell script in ksh on an AIX system. The goal is to create a directory that may or may not already exist. Using the `mkdir` command directly is not feasible because it throws an error when the directory exists. I'm looking for a way to check if the directory doesn't exist before attempting to create it, or a method to suppress the error that mkdir throws when it runs into an existing directory.
A straightforward approach is to use the `if` statement to check for the directory's existence before using `mkdir`. Here's what I've attempted so far:

Code:
then
mkdir "/path/to/mydir"
fi

However, I'm unsure if this is the best practice for handling this situation in ksh. Could there be a more efficient or cleaner way to accomplish this task?
Reply
#2
That is a common method for conditionally creating a directory, but you're not handling any potential errors that might occur during the directory creation process. It is good practice to check the exit status of mkdir as well. Consider using the following enhancement to your script:

Code:
then
mkdir "/path/to/mydir"
2 > /dev/null
if [$ ? -ne 0];
then
echo "An error occurred while creating the directory."
fi
else
    echo "Directory already exists. No action taken."
fi

Redirecting stderr to `/dev/null` with `2>/dev/null` is a way to suppress warning messages, and checking `$?` allows you to handle the case where `mkdir` fails for reasons other than the directory already existing.
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)