← Back to all snippets
BASH

Parse Command Line Arguments

Learn to parse command-line arguments in Bash scripts, enabling flexible input for flags and options, a common task for developers automating tasks.

#!/bin/bash

# Default values
VERBOSE=false
ENVIRONMENT="development"
PORT=8080

# Parse arguments
while [[ "$#" -gt 0 ]]; do
    case "$1" in
        -v|--verbose) VERBOSE=true ;;
        -e|--env) ENVIRONMENT="$2"; shift ;;
        -p|--port) PORT="$2"; shift ;;
        *) echo "Unknown parameter passed: $1"; exit 1 ;;
    esac
    shift
done

echo "Verbose: $VERBOSE"
echo "Environment: $ENVIRONMENT"
echo "Port: $PORT"

# Example usage:
# ./my_script.sh -v -e production -p 3000
# ./my_script.sh --env staging
How it works: This script demonstrates how to parse command-line arguments using a `while` loop and `case` statement. It sets default values for variables like `VERBOSE`, `ENVIRONMENT`, and `PORT`. Arguments like `-v` or `--verbose` act as boolean flags, while `-e` or `--env` and `-p` or `--port` accept values. This pattern is crucial for creating flexible and configurable Bash scripts, allowing developers to customize script behavior without editing the code directly.

Need help integrating this into your project?

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

Hire DigitalCodeLabs