小能豆

How to mkdir only if a directory does not already exist?

shell

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?


阅读 234

收藏
2023-12-26

共1个答案

小能豆

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:

#!/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" ]]: This test checks if the directory exists. If it doesn’t exist (! -d), the mkdir command is executed.
  • mkdir "$directory": This creates the directory.
  • If the directory already exists, the script prints a message indicating that no action is taken.

This way, you can safely create a directory only if it doesn’t already exist.

2023-12-26