0
0
Bash Scriptingscripting~5 mins

Long option parsing in Bash Scripting

Choose your learning style9 modes available
Introduction

Long option parsing helps scripts understand commands like --help or --version. It makes scripts easier to use and remember.

You want users to run your script with clear options like <code>--file</code> instead of just <code>-f</code>.
Your script needs to accept multiple options with descriptive names.
You want to provide a friendly way to show help or version info.
You want to avoid confusion with short options that look similar.
You want to handle options with or without values, like <code>--output=filename</code>.
Syntax
Bash Scripting
# Use a while loop and case statement to check $1
while [[ "$1" != "" ]]; do
  case $1 in
    --option) # handle option
      ;; 
    --option=*) # handle option with value
      ;; 
    --help) # show help
      ;; 
    *) # unknown option
      ;; 
  esac
  shift
 done

Use shift to move to the next argument after processing one.

Use case to match long options easily.

Examples
Simple example to print messages for --help and --version.
Bash Scripting
while [[ "$1" != "" ]]; do
  case $1 in
    --help)
      echo "Show help"
      ;;
    --version)
      echo "Show version"
      ;;
  esac
  shift
done
Example to get a value from an option like --file=example.txt.
Bash Scripting
while [[ "$1" != "" ]]; do
  case $1 in
    --file=*)
      filename="${1#*=}"
      echo "File is $filename"
      ;;
  esac
  shift
done
Example showing a flag option --verbose and an option with value --output=filename.
Bash Scripting
while [[ "$1" != "" ]]; do
  case $1 in
    --verbose)
      verbose=true
      ;;
    --output=*)
      output_file="${1#*=}"
      ;;
  esac
  shift
done
Sample Program

This script reads long options --verbose and --output=filename. It shows how to handle flags and options with values. It also shows a help message with --help.

Bash Scripting
#!/bin/bash

verbose=false
output_file="default.txt"

while [[ "$1" != "" ]]; do
  case $1 in
    --help)
      echo "Usage: script.sh [--verbose] [--output=filename]"
      exit
      ;;
    --verbose)
      verbose=true
      ;;
    --output=*)
      output_file="${1#*=}"
      ;;
    *)
      echo "Unknown option: $1"
      exit 1
      ;;
  esac
  shift
 done

if $verbose; then
  echo "Verbose mode is ON"
else
  echo "Verbose mode is OFF"
fi

echo "Output file is: $output_file"
OutputSuccess
Important Notes

Always use quotes around variables like "$1" to avoid errors with spaces.

Use ${1#*=} to get the part after = in options like --output=file.

Remember to shift to move to the next argument after processing one.

Summary

Long option parsing makes scripts easier to use with clear option names.

Use a while loop and case to check each argument.

Handle options with and without values by matching patterns like --option and --option=value.