← Back to all snippets
BASH

Conditional Script Execution Based on File or Directory Existence

Enhance script robustness by using Bash conditionals to check for file or directory existence before executing commands, preventing errors and adapting to various project structures.

#!/bin/bash
# Example: Check for a .env file and a 'node_modules' directory

ENV_FILE=".env"
BUILD_DIR="dist"
NODE_MODULES_DIR="node_modules"

# Check if .env file exists
if [ -f "$ENV_FILE" ]; then
    echo "'.env' file found. Sourcing environment variables."
    # source "$ENV_FILE" # Be cautious with sourcing for production, use specific variables.
    # Example: MY_APP_KEY=$(grep MY_APP_KEY "$ENV_FILE" | cut -d '=' -f2)
else
    echo "Warning: '.env' file not found. Script might not have all expected variables."
fi

echo "" # Newline for readability

# Check if a 'node_modules' directory exists
if [ -d "$NODE_MODULES_DIR" ]; then
    echo "'$NODE_MODULES_DIR' directory found. Assuming dependencies are installed."
    # npm run build # Example: run build process
else
    echo "Error: '$NODE_MODULES_DIR' not found. Please run 'npm install'."
    exit 1
fi

echo "" # Newline for readability

# Check if a 'dist' directory exists and is not empty before attempting to deploy
if [ -d "$BUILD_DIR" ] && [ "$(ls -A $BUILD_DIR)" ]; then
    echo "'$BUILD_DIR' directory found and is not empty. Ready for deployment."
    # rsync -avz "$BUILD_DIR/" user@remote:/var/www/html/dist/ # Example: deploy
else
    echo "Warning: '$BUILD_DIR' directory is missing or empty. Build might be required."
fi

echo "Script finished."
How it works: This script demonstrates how to use Bash conditional statements (`if [ -f FILE ]` for files, `if [ -d DIR ]` for directories) to check for the existence of specific files or directories. This is crucial for building robust scripts that adapt to different project states or configurations, preventing errors by ensuring prerequisites are met before proceeding with operations like dependency management or deployment.

Need help integrating this into your project?

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

Hire DigitalCodeLabs