BASH

Parse Command Line Arguments in Bash

Learn to parse command-line arguments using `getopts` in Bash, enabling flexible and configurable script execution for various web development automation tasks and utilities.

#!/bin/bash

# Default values
VERBOSE=0
ENV="development"
CONFIG_FILE=""

# Parse arguments using getopts
while getopts "ve:c:" opt; do
    case ${opt} in
        v ) # Verbose mode
            VERBOSE=1
            ;;
        e ) # Environment (e.g., dev, prod)
            ENV=${OPTARG}
            ;;
        c ) # Configuration file path
            CONFIG_FILE=${OPTARG}
            ;;
        \? ) # Invalid option
            echo "Usage: $0 [-v] [-e <environment>] [-c <config_file>]"
            exit 1
            ;;
    esac
done
shift $((OPTIND -1)) # Shift positional parameters to exclude processed options

echo "Script parameters:"
echo "Verbose: ${VERBOSE}"
echo "Environment: ${ENV}"
echo "Config File: ${CONFIG_FILE}"

if [ "${VERBOSE}" -eq 1 ]; then
    echo "Running in verbose mode..."
fi

# Example usage of parameters
if [ -n "${CONFIG_FILE}" ] && [ -f "${CONFIG_FILE}" ]; then
    echo "Loading configuration from: ${CONFIG_FILE}"
    # Source the config file or process it as needed
    # source "${CONFIG_FILE}"
else
    echo "No valid configuration file provided or found."
fi

echo "Remaining positional arguments: $@"
How it works: This Bash script demonstrates how to parse command-line arguments using the `getopts` utility, which is ideal for handling short, single-character options. It defines default values for variables like `VERBOSE`, `ENV`, and `CONFIG_FILE`, then updates them based on the provided arguments. The `shift` command removes the processed options from the parameter list, leaving only positional arguments. This allows you to create flexible scripts that can be configured at runtime, a common need for deployment and utility scripts.

Need help integrating this into your project?

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

Hire DigitalCodeLabs