How to create a directory only if it doesn’t already exist in KornShell (ksh) on AIX?
I’m writing a shell script for KornShell (ksh) on AIX and need to use the mkdir command to create a directory. However, the directory might already exist, and in that case, I don’t want to perform any action. I’m looking for either:
- A way to test if the directory doesn’t exist before creating it
- A method to suppress the “File exists” error that mkdir throws when attempting to create an existing directory
What’s the best approach to handle this scenario in a KornShell script on AIX?
The best approach to create a directory only if it doesn’t exist in KornShell on AIX is to use the mkdir -p command, which automatically handles existing directories without errors, or to first check for directory existence using a conditional statement before attempting creation.
Contents
- Using mkdir -p for Automatic Directory Creation
- Checking Directory Existence First
- Error Handling Approaches
- AIX-Specific Considerations
- Complete Script Examples
- Best Practices
Using mkdir -p for Automatic Directory Creation
The simplest and most common method is using the -p (parents) flag with the mkdir command. This flag tells mkdir to create any necessary parent directories and to ignore the error if the target directory already exists.
mkdir -p /path/to/directory
Key advantages of this approach:
- No error messages when the directory already exists
- Creates parent directories automatically if needed
- Atomic operation - either succeeds completely or does nothing
- Works consistently across different Unix systems including AIX
On AIX, the mkdir -p command is part of the standard utilities and is well-supported. The command will return success (exit code 0) whether the directory already existed or was newly created.
# This will work without errors on AIX
mkdir -p /opt/myapp/logs
mkdir -p /tmp/working_directory
The -p flag is POSIX-compliant and is the recommended approach for most modern shell scripting scenarios.
Checking Directory Existence First
For more explicit control or when you need to perform additional logic, you can test for directory existence before attempting creation using conditional statements.
Using the test command
if [ ! -d "/path/to/directory" ]; then
mkdir "/path/to/directory"
fi
Using the conditional operator
[ ! -d "/path/to/directory" ] && mkdir "/path/to/directory"
Using the case statement
case "$(stat -f "%HT" /path/to/directory 2>/dev/null)" in
"directory") echo "Directory already exists" ;;
"") mkdir "/path/to/directory" ;;
*) echo "Path exists but is not a directory" ;;
esac
Advantages of the conditional approach:
- More explicit control over the flow
- Allows for additional logic when the directory exists
- Better for debugging and logging
- More readable in complex scripts
Error Handling Approaches
Suppressing mkdir errors with shell redirection
If you prefer to use the basic mkdir command without -p, you can redirect the error output to /dev/null:
mkdir /path/to/directory 2>/dev/null
However, this approach has limitations:
- It suppresses all errors, not just “File exists”
- You won’t know if the directory was actually created or already existed
- It doesn’t handle parent directory creation
Using mkdir with error checking
mkdir /path/to/directory 2>/dev/null
if [ $? -ne 0 ] && [ ! -d "/path/to/directory" ]; then
echo "Error creating directory"
exit 1
fi
Using trap for error handling
set -e # Exit on error
trap 'echo "Directory creation failed"' ERR
mkdir -p /path/to/directory
AIX-Specific Considerations
AIX mkdir behavior
AIX’s mkdir command is generally POSIX-compliant, but there are some specific considerations:
- Filesystem differences: AIX supports various filesystems (JFS2, NFS, etc.) that may have slightly different behaviors
- Permission handling: AIX has specific permission inheritance rules
- Symbolic links: AIX handles symbolic links differently than some other Unix variants
AIX-specific directory creation patterns
# AIX-specific: Check for filesystem type
if [ "$(df -T /path/to | tail -1 | awk '{print $2}')" = "jfs2" ]; then
echo "Creating directory on JFS2 filesystem"
mkdir -p /path/to/directory
fi
# AIX-specific: Set appropriate permissions
mkdir -p /path/to/directory
chmod 755 /path/to/directory
chown appuser:appgroup /path/to/directory
Performance considerations on AIX
For large-scale directory creation on AIX systems, consider:
# Use bulk operations when creating multiple directories
for dir in /path/to/dir1 /path/to/dir2 /path/to/dir3; do
mkdir -p "$dir"
done
Complete Script Examples
Example 1: Basic directory creation function
#!/bin/ksh
# Function to create directory only if it doesn't exist
create_dir_if_not_exists() {
local dir_path="$1"
if [ ! -d "$dir_path" ]; then
mkdir -p "$dir_path"
if [ $? -eq 0 ]; then
echo "Created directory: $dir_path"
return 0
else
echo "Failed to create directory: $dir_path"
return 1
fi
else
echo "Directory already exists: $dir_path"
return 0
fi
}
# Usage
create_dir_if_not_exists "/opt/myapp/logs"
create_dir_if_not_exists "/tmp/working"
Example 2: AIX-specific script with error handling
#!/bin/ksh
# AIX directory creation script with comprehensive error handling
LOG_DIR="/var/log/myapp"
DATA_DIR="/data/myapp"
CONFIG_DIR="/etc/myapp"
# Function to create directory with proper ownership
create_app_dir() {
local dir_path="$1"
local owner="$2"
local group="$3"
local permissions="$4"
if [ ! -d "$dir_path" ]; then
mkdir -p "$dir_path"
if [ $? -ne 0 ]; then
echo "ERROR: Failed to create directory $dir_path" >&2
return 1
fi
# Set ownership and permissions
chown "$owner:$group" "$dir_path"
chmod "$permissions" "$dir_path"
fi
return 0
}
# Create required directories
create_app_dir "$LOG_DIR" "root" "system" "755" || exit 1
create_app_dir "$DATA_DIR" "appuser" "appgroup" "775" || exit 1
create_app_dir "$CONFIG_DIR" "root" "system" "755" || exit 1
echo "All directories created successfully"
Example 3: Using arrays for multiple directories
#!/bin/ksh
# Create multiple directories with consistent handling
declare -a directories=(
"/opt/application/bin"
"/opt/application/config"
"/opt/application/temp"
"/opt/application/logs"
"/var/run/application"
)
for dir in "${directories[@]}"; do
if [ ! -d "$dir" ]; then
mkdir -p "$dir"
echo "Created: $dir"
else
echo "Exists: $dir"
fi
done
Best Practices
Recommended approaches
- Use
mkdir -pas the default approach - It’s the most reliable and portable method - Always use absolute paths in scripts to avoid ambiguity
- Check return values in production scripts for proper error handling
- Set appropriate permissions after directory creation
Code quality considerations
# Good practice: Use variables for paths
APP_HOME="/opt/myapp"
LOG_DIR="$APP_HOME/logs"
DATA_DIR="$APP_HOME/data"
# Good practice: Validate input
if [ -z "$1" ]; then
echo "Usage: $0 <directory_path>"
exit 1
fi
# Good practice: Use proper quoting
mkdir -p "$directory_path"
Performance optimization for AIX
When creating many directories on AIX:
- Minimize filesystem operations by grouping related directories
- Use parallel creation for independent directories
- Consider bulk operations when possible
# Efficient creation of multiple directories
directories=(
"/opt/app1/logs"
"/opt/app1/data"
"/opt/app2/logs"
"/opt/app2/data"
)
# Create all directories in one operation
mkdir -p "${directories[@]}"
Security considerations
# Secure directory creation
SECURE_DIR="/secure/application"
mkdir -p "$SECURE_DIR"
chmod 700 "$SECURE_DIR" # Restrict access
chown appuser:securegroup "$SECURE_DIR"
Sources
- AIX 7.2 Commands Reference - mkdir
- KornShell User’s Guide - Conditional Statements
- POSIX Standard - mkdir Utility
- AIX System Administration Guide - Filesystems
- Shell Scripting Best Practices - IBM Developer
Conclusion
To create a directory only if it doesn’t already exist in KornShell on AIX, the most effective approaches are:
-
Use
mkdir -p- This is the simplest and most reliable method that handles existing directories gracefully and creates parent directories as needed. -
Check directory existence first - Use conditional statements like
[ ! -d "/path" ]before callingmkdirwhen you need more control or additional logic. -
Implement proper error handling - For production scripts, always check return values and implement appropriate error handling.
The mkdir -p approach is generally recommended for its simplicity and reliability, while the conditional approach offers more flexibility for complex scenarios. Both methods work well on AIX systems and are compatible with KornShell scripting practices.
For best results in AIX environments, consider filesystem-specific characteristics and set appropriate permissions and ownership after directory creation. Always test your scripts in a development environment before deploying to production systems.