I am writing a shell script to run under the KornShell (ksh) on AIX. I would like to use the mkdir command to create a directory. But the directory may already exist, in which case I do not want to do anything. So I want to either test to see that the directory does not exist, or suppress the “File exists” error that mkdir throws when it tries to create an existing directory.
How can I best do this?
In the KornShell (ksh) on AIX, you can use the [[ -d dir ]] test to check whether a directory exists before attempting to create it with mkdir. If the directory already exists, the mkdir command won’t be executed. Here’s an example:
[[ -d dir ]]
mkdir
#!/bin/ksh directory="/path/to/your/directory" if [[ ! -d "$directory" ]]; then mkdir "$directory" echo "Directory created successfully." else echo "Directory already exists. No action taken." fi
In this script:
[[ -d "$directory" ]]
! -d
mkdir "$directory"
This way, you can safely create a directory only if it doesn’t already exist.