# Argument parser for bash scripts v1.6 ## Usage ```shell # 1. add these lines after shebang: __RAW_ARGS__=("$@") source args.sh # 2. read arguments as flags: arg a 1 flag_a echo "Flag -a has value '$flag_a'" echo "Flag -a has value '$(arg a 1)'" arg b 1 flag_b echo "Flag -b has value '$flag_b'" echo "Flag -b has value '$(arg b 1)'" arg c 1 flag_c echo "Flag -c has value '$flag_c'" echo "Flag -c has value '$(arg c 1)'" arg d 1 flag_d echo "Flag -d has value '$flag_d'" echo "Flag -d has value '$(arg d 1)'" argl flag1 1 flag_1 echo "Flag --flag1 has value '$flag_1'" echo "Flag --flag1 has value '$(argl flag1 1)'" argl flag2 1 flag_2 echo "Flag --flag2 has value '$flag_2'" echo "Flag --flag2 has value '$(argl flag2 1)'" # 3. and/or read arguments' values: arg a 0 arg_a echo "Arg -a has value '$arg_a'" echo "Arg -a has value '$(arg a 0)'" arg b 0 arg_b echo "Arg -b has value '$arg_b'" echo "Arg -b has value '$(arg b 0)'" argl arg1 0 arg_1 echo "Arg --arg1 has value '$arg_1'" echo "Arg --arg1 has value '$(argl arg1 0)'" argl arg2 0 arg_2 echo "Arg --arg2 has value '$arg_2'" echo "Arg --arg2 has value '$(argl arg2 0)'" ``` ## How it works 1. Short arguments can be specified contiguously or separately and their order does not matter, but before each of them (or the first of them) one leading dash must be specified. > Valid combinations: `-a -b -c`, `-cba`, `-b -azc "value of z"` 2. Short arguments can have values and if are - value must go next to argument itself. > Valid combinations: `-ab avalue`, `-ba avalue`, `-a avalue -b` 3. Long arguments cannot be combined like short ones and each of them must be specified separately with two leading dashes. > Valid combinations: `--foo --bar`, `--bar --foo` 4. Long arguments can have a value which must be specified after `=`. > Valid combinations: `--foo value --bar`, `--bar --foo=value` 5. If arg value may contain space then value must be "double-quoted". 6. You can use arg() or argl() to check presence of any arg, no matter if it has value or not. More info: * πŸ‡·πŸ‡Ί [axenov.dev/bash-args](https://axenov.dev/bash-args/) * πŸ‡ΊπŸ‡Έ [axenov.dev/en/bash-processing-arguments-in-a-script-when-called-from-the-shell/](https://axenov.dev/en/bash-processing-arguments-in-a-script-when-called-from-the-shell) Tested in Ubuntu 20.04.2 LTS in: ``` bash 5.0.17(1)-release (x86_64-pc-linux-gnu) and later zsh 5.8 (x86_64-ubuntu-linux-gnu) and later ``` ## Version history ``` v1.0 - initial v1.1 - arg(): improved skipping uninteresting args - arg(): check next arg to be valid value v1.2 - removed all 'return' statements - arg(): error message corrected - new examples v1.3 - argl(): improved flag check - some text corrections v1.4 - new function argn() - some text corrections v1.5 - arg(), grep_match(): fixed searching for -e argument - grep_match(): redirect output into /dev/null v1.6 - removed useless argn() - arg() and argl() refactored and now support values with whitespaces ```