BASH
Check and Create Directory or File if Not Exists
Bash script to safely check if a directory or file exists and create it if it doesn't, preventing common script errors in automation workflows.
#!/bin/bash
# Define paths
DIR_PATH="/var/log/myapp"
FILE_PATH="/var/log/myapp/app.log"
# --- Check and create directory if it doesn't exist ---
if [ ! -d "$DIR_PATH" ]; then
echo "Directory '$DIR_PATH' does not exist. Creating..."
mkdir -p "$DIR_PATH" || { echo "Error: Failed to create directory '$DIR_PATH'"; exit 1; }
echo "Directory '$DIR_PATH' created successfully."
else
echo "Directory '$DIR_PATH' already exists."
fi
# --- Check and create file if it doesn't exist ---
if [ ! -f "$FILE_PATH" ]; then
echo "File '$FILE_PATH' does not exist. Creating..."
touch "$FILE_PATH" || { echo "Error: Failed to create file '$FILE_PATH'"; exit 1; }
echo "File '$FILE_PATH' created successfully."
else
echo "File '$FILE_PATH' already exists."
fi
echo "
Setup complete. Both directory and file are ready for use."
How it works: This snippet provides a robust way to ensure that a required directory and/or file exist before your script proceeds. It uses `[ ! -d "$DIR_PATH" ]` to check for directory existence and `[ ! -f "$FILE_PATH" ]` for files. If they don't exist, `mkdir -p` creates the directory (including parent directories if needed), and `touch` creates an empty file. The `|| { ...; exit 1; }` construct ensures that the script exits gracefully with an error message if creation fails, preventing subsequent commands from operating on non-existent paths.