BudiBadu Logo
Samplebadu

Bash by Example: Check Directory Exists

Bash 5.0+

Verifying directory existence and creating it if missing using conditional logic with mkdir -p for parent directory creation, understanding the idempotent nature of mkdir -p that prevents errors when directories exist, implementing reliable directory setup in deployment scripts, and ensuring proper permissions for newly created directories.

Code

#!/bin/bash

dirname="logs"

# Check if directory exists
if [ -d "$dirname" ]; then
    echo "Directory $dirname exists."
else
    echo "Directory not found."
fi

# Create directory if it doesn't exist
if [ ! -d "$dirname" ]; then
    echo "Creating directory..."
    mkdir -p "$dirname"
fi

# Check if directory is empty
if [ -z "$(ls -A $dirname)" ]; then
   echo "$dirname is empty"
else
   echo "$dirname is not empty"
fi

rmdir "$dirname"

Explanation

To check for directories, use the -d operator. This ensures the path exists and is specifically a directory.

A very common pattern in scripts is to check if a directory exists and create it if it doesn't. This prevents mkdir from throwing an "File exists" error, although mkdir -p also handles that gracefully.

Checking if a directory is empty is slightly trickier. ls -A lists all files (including hidden ones, but excluding . and ..). If the output of that command is empty string (checked with -z), the directory is empty.

Code Breakdown

6
[ -d ... ] returns true only if the path is a directory.
15
mkdir -p creates parent directories as needed and doesn't complain if the directory already exists.
19
ls -A is used because ls alone might miss hidden files (dotfiles), giving a false empty result.