Bash patterns I use #2: argument parsing.

Bash patterns I use #2: argument parsing.

This is the 2nd part of the "Bash patterns I use" series. The first pattern covered Limiting parallelism in Bash.

In this part I'll show what I typically use when to parse arguments. This is inspired by this very excellent StackOverflow answer to the question "How do I parse command line arguments in Bash?".

I commonly use this as basis:

for arg in "$@"; do
case $arg in
   --dsn=*)
   DSN="${arg#*=}"
   shift
   ;;
   --help)
   <call a help function>
   ;;
   *)
   echo "Unknown argument provided."
   <call a help function>
   exit 1
   ;;
esac
done

The user would therefore call ./something.sh --dsn=postgresql://postgres@localhost/dbname and then, within the script, one can make use of DSN.

I typically add at least one more function to make things required. For instance:

function exit_if_not_set {
   if [ -z "$1" ]; then
      echo "Error: $2"
      <call help function>
      exit 1
   fi
}

[arg parsing goes here]

exit_if_not_set "$DSN" "DSN not provided"

In this example, it does not parse the DSN for correctness. But at least it makes --dsn be required.

Notes

  • Photo by Iva Muškić from Pexels