BASH

Manage Config Files with Conditional Creation

Create and manage application configuration files or environment variable files in Bash, ensuring they exist and are populated with default content if missing.

#!/bin/bash

# Define the path for the configuration file
CONFIG_FILE="./.env.local"

# Check if the configuration file already exists
if [ -f "$CONFIG_FILE" ]; then
    echo "Configuration file '$CONFIG_FILE' already exists. Skipping creation."
    # Optional: You could add logic here to check content, update, etc.
    # Example: Append a new variable if it's not present
    # if ! grep -q "NEW_VARIABLE" "$CONFIG_FILE"; then
    #    echo "Appending NEW_VARIABLE to $CONFIG_FILE"
    #    echo "NEW_VARIABLE=some_value" >> "$CONFIG_FILE"
    # fi
else
    echo "Configuration file '$CONFIG_FILE' not found. Creating with default content."
    # Create the file with some default content
    cat <<EOF > "$CONFIG_FILE"
# Local Environment Variables
DB_HOST=localhost
DB_USER=root
DB_PASSWORD=password
APP_DEBUG=true

# Add more variables as needed
EOF

    if [ $? -eq 0 ]; then
        echo "Successfully created '$CONFIG_FILE'."
    else
        echo "Error: Failed to create '$CONFIG_FILE'." >&2
        exit 1
    fi
fi

echo "Current content of $CONFIG_FILE:"
cat "$CONFIG_FILE"
How it works: This script helps manage critical configuration files, such as `.env` files, by conditionally creating them if they don't exist. It first checks for the presence of the specified `CONFIG_FILE`. If the file is missing, it uses a 'here-document' (`cat <<EOF > ...`) to create the file and populate it with predefined default content, like environment variables. If the file already exists, it simply acknowledges its presence, preventing accidental overwrites. This is invaluable for setting up consistent development environments or deploying applications that require initial configuration.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs