BASH
Check File or Directory Existence and Create if Missing
Ensure critical files or directories exist before script execution, creating them if necessary, to prevent errors in your web development workflows.
#!/bin/bash
REQUIRED_DIR="./logs"
REQUIRED_FILE="./config/app.conf"
# Function to check and create directory
ensure_directory_exists() {
local dir="$1"
if [ ! -d "$dir" ]; then
echo "Directory '$dir' does not exist. Creating..."
mkdir -p "$dir" || {
echo "Error: Failed to create directory '$dir'." >&2
exit 1
}
echo "Directory '$dir' created successfully."
else
echo "Directory '$dir' already exists."
fi
}
# Function to check and create file
ensure_file_exists() {
local file="$1"
local content="$2"
if [ ! -f "$file" ]; then
echo "File '$file' does not exist. Creating..."
# Create parent directory if it doesn't exist
local parent_dir=$(dirname "$file")
ensure_directory_exists "$parent_dir"
echo -e "$content" > "$file" || {
echo "Error: Failed to create file '$file'." >&2
exit 1
}
echo "File '$file' created successfully with default content."
else
echo "File '$file' already exists."
fi
}
# Example Usage:
# Ensure a log directory exists
ensure_directory_exists "$REQUIRED_DIR"
# Ensure a config directory and file exist with default content
DEFAULT_CONF_CONTENT="# Application Configuration
DEBUG=true
PORT=8080"
ensure_file_exists "$REQUIRED_FILE" "$DEFAULT_CONF_CONTENT"
echo "
All required files and directories are in place."
# You can now proceed with your script logic, assuming these are available.
# Example: Cat the config file content
if [ -f "$REQUIRED_FILE" ]; then
echo "
--- Content of $REQUIRED_FILE ---"
cat "$REQUIRED_FILE"
echo "------------------------------------"
fi
How it works: This script provides two functions, `ensure_directory_exists` and `ensure_file_exists`, to verify the presence of specified paths and create them if they do not exist. `ensure_directory_exists` uses `mkdir -p` to create a directory and any necessary parent directories, making it robust. `ensure_file_exists` first ensures the parent directory of the file exists, then creates the file, optionally populating it with default content. Both functions include basic error handling and informative messages, making them useful for setting up environments or ensuring dependencies before script execution.