Attribution with conditions & description of options and flags
- BAsh interpreter - Let the source file be in the PATH environment variableHere is a quick script opt_demo to introduce optparse:
#!/bin/bash # Mandatory: opts & flags array opts=( "n:'number between 5 and 10' [[ n -lt 10 && n -gt 5 ]]" "x:'low-case string' [[ x =~ ^[a-z]+$ ]]" ) # -h flag is by default flags=("A:Affect all options as variables") # Optional description function about() { echo "Demonstration script" } # Let the script do the job source optparse # If you want to affect options as variables -A: [[ "${OPTS[A]}" =~ true ]] && affect_opt echo "n="$n # TODO CODE HERE :) exit 0
Some outputs:
$ opt_demo -h Usage: ./opt_demo [options] [flags] Demonstration script Options: -n 'number between 5 and 10' [[ n -lt 10 && n -gt 5 ]] -x 'low-case string' [[ x =~ ^[a-z]+$ ]] Flags: -A false Affect all options as variables -h true
Given conditions are tested at first:
$ opt_demo -x coucou -n 3 Condition failed: [[ 3 -lt 10 && 3 -gt 5 ]]
No output, arguments are good to be used:
$ opt_demo -x coucou -n 6
We can affect all options as variables using -A:
$ opt_demo -n 6 -A n=6
Description part is a string without empty spaces (the trick to have spaces on the screen is to use AltGr+SpaceBar when you type it).