The Bash Argsparse Library 1.8
An high level argument parsing library for bash.
Loading...
Searching...
No Matches
argsparse.sh File Reference

Bash Argsparse Library. More...

Functions

 __argsparse_has_array_item (array_name, item)
 
 __argsparse_index_of (value, values...)
 Tells if a value is found in a set of other values.
 
 __argsparse_is_array_declared (name)
 
 __argsparse_join_array (c, strings...)
 join multiple strings by a char.
 
 __argsparse_parse_options_env_and_defaults ()
 set options from environment and from default values.
 
 __argsparse_parse_options_no_usage ()
 Parse options without triggering usage.
 
 __argsparse_parse_options_valuecheck (option, value)
 Check a value given to an option.
 
 __argsparse_set_option (option)
 Resolv option-specific setter function and invoke it.
 
 __argsparse_values_array_identifier (option)
 Prints the name of the array containing all user-declared acceptable values for an option.
 
 argsparse_allow_no_argument (string)
 Allow empty command lines to run.
 
 argsparse_are_environment_variables_enabled ()
 Tell if option setting through environment variables is enabled or not.
 
 argsparse_check_option_type (type, value)
 Check if a value matches a given type.
 
 argsparse_describe_parameters (param...)
 Describe non-option positionnal parameters.
 
 argsparse_get_cumulative_array_name (option)
 Print the name of the array used for "cumulative" and "cumulativeset" options.
 
 argsparse_has_option_property (option, property)
 Determine if an option has a property.
 
 argsparse_is_option_set (option)
 Return True if an option has been set on the command line.
 
 argsparse_maximum_parameters (unsigned_int)
 Set the maximum number of non-option parameters expected on the command line.
 
 argsparse_minimum_parameters (unsigned_int)
 Set the minimum number of non-option parameters expected on the command line.
 
 argsparse_option_description (option)
 Prints to stdout the description of given option.
 
 argsparse_option_environment_variable (option)
 Give the content of the environment variable that can be used to set a given option.
 
 argsparse_option_environment_variable_name (option)
 Give the environment variable name linked to an option.
 
 argsparse_option_to_identifier (option)
 Give the identifier name associated to an option.
 
 argsparse_parse_options (parameters...)
 Parse program options.
 
 argsparse_report (option...)
 Prints a basic report of all passed options.
 
 argsparse_set_alias (option)
 "alias" property specific option-setting hook.
 
 argsparse_set_cumulative_option (option, value)
 "cumulative" property specific option-setting hook.
 
 argsparse_set_cumulativeset_option (option, value)
 "cumulativeset" property specific option-setting hook.
 
 argsparse_set_option (option, value)
 Default option-setting hook.
 
 argsparse_set_option_from_environment_value (option, value)
 Give a value to an option, from environment variable value.
 
 argsparse_set_option_property (property, option...)
 Enable a property to a list of options.
 
 argsparse_set_option_with_value (option, value)
 "value" property specific option-setting hook.
 
 argsparse_set_option_without_value (option)
 The option-setting hook for options not accepting values.
 
 argsparse_short_to_long (char)
 
 argsparse_usage ()
 A generic help message generated from the options and their descriptions.
 
 argsparse_usage_long ()
 Fully describe the program syntax and options to the end-user.
 
 argsparse_usage_short ()
 Print a short description of the program syntax.
 
 argsparse_use_environment_variables (prefix)
 Enable option setting through environment variables.
 
 argsparse_use_option (optstring, description, property...)
 Define a new option.
 
 set_option_help ()
 Default trigger for –help option.
 
 usage ()
 Default usage function.
 

Variables

String __argsparse_environment_variable_prefix
 The prefix for option-setting environment variables.
 
Integer __argsparse_maximum_parameters = 1000000
 Internal use only.
 
Integer __argsparse_minimum_parameters = 0
 Internal use only.
 
String AssociativeArray __argsparse_options_default_values
 Internal use only.
 
String AssociativeArray __argsparse_options_descriptions
 Internal use only.
 
String AssociativeArray __argsparse_options_properties
 Internal use only.
 
String Array __argsparse_parameters_description
 Internal use only.
 
String AssociativeArray __argsparse_short_options
 Internal use only.
 
String AssociativeArray __argsparse_tmp_identifiers
 Internal use.
 
ReadOnly String argsparse_pgm
 The name of the program currently using argsparse.
 
String argsparse_usage_description
 Usage description additionnal string.
 
ReadOnly String ARGSPARSE_VERSION = 1.8
 argsparse version number
 
String AssociativeArray program_options
 Options values.
 
String Array program_params
 Positionnal parameters of the script.
 

Detailed Description

Bash Argsparse Library.

Author
Damien Nadé bash-.nosp@m.args.nosp@m.parse.nosp@m.@liv.nosp@m.na.or.nosp@m.g
Version
1.8
URL
https://github.com/Anvil/bash-argsparse
Purpose

To replace the option-parsing and usage-describing functions commonly rewritten in all scripts.

Note
This library is implemented for bash version 4. Prior versions of bash will fail at interpreting that code.
The extglob shell option will be enabled and posix mode will be disabled when loading the library. Changing those settings afterwards will make the library execution fail.
Usage
Use the argsparse_use_option() function to declare your options with their single letter counterparts, along with their description.
The argsparse_use_option() syntax is:
argsparse_use_option "optstring" "option description string" \
[ "property" ... ] [ "optional default value" ]
argsparse_use_option(optstring, description, property...)
Define a new option.
Definition argsparse.sh:777
An "optstring" is of the form "som=estring:". This would declare a long option named somestring. The ending ":" is optional and, if present, means the long option expects a value on the command line. The "=" char is also optional and means the immediatly following letter is the short single-letter equivalent option of –something.
The "something" string must only contains ASCII letters/numbers/dash/underscore characters.
Note
What is referred later as "option" or "option name" (or even "long option name") is the optstring without the ':' and '=' characters.
Options may have properties.

Properties are set either at option declarations through the argsparse_use_option() function, or using the argsparse_set_option_property() function

The currently supported properties are:

  • "hidden"
    An hidden option will not be shown in usage.
  • "mandatory"
    An option marked as mandatory is required on the command line. If a mandatory option is omited by the user, usage() will be triggered by argsparse_parse_options().
  • "value"
    On the command line, the option will require a value. Same effect if you end your optstring with a ':' char.
  • "default:<defaultvalue>"
    The default value for the option.
  • "short:<char>"
    The short single-letter equivalent of the option.
  • "type:<typename>"
    Give a type to the option value. User input value will be checked against built-in type verifications or the "check_type_<typename>" function. You cannot override a built-in type. Built-in types are:
    • file
    • directory
    • pipe
    • terminal
    • socket
    • link
    • char
    • unsignedint
    • uint
    • integer
    • int
    • hexa
    • ipv4
    • ipv6
    • ip
    • hostname
    • host
    • portnumber
    • port
    • username
    • group
    • date
  • "exclude:<option> <option>"
    The exclude property value is a space-separated list of other options. User wont be able to provided two mutually exclusive options on the command line.
    e.g: if you set exclude property for the –foo option this way:
    argsparse_set_option_property "exclude:opt1 opt2" foo
    argsparse_set_option_property(property, option...)
    Enable a property to a list of options.
    Definition argsparse.sh:623
    Then –opt1 and –foo are not allowed on the same command line invokation. And same goes for –opt2 and –foo. This foo exclude property setting wouldnt make –opt1 and –opt2, mutually exclusive though.
  • "alias:<option> <option>"
    This property allows an option to set multiple other without-value options instead. Recursive aliases are permitted but no loop detection is made, so be careful.
    e.g: if you declare an option 'opt' like this:
    argsparse_use_option opt "my description" "alias:opt1 opt2"
    Then if the user is doing –opt on the command line, it will be as if he would have done –opt1 –opt2
  • cumulative
    Implies 'value'. Everytime a cumulative option "optionname" is passed on the command line, the value is stored at the end of an array named "cumulated_values_<optionname>".
    e.g: for a script with an opt1 option declared this way:
    argsparse_use_option opt1 "some description" cumulative
    and invoked with:
    --opt1 value1 --opt1 value2
    after argsparse_parse_options(), "${cumulated_values_opt1[0]}" will expand to value1, and ${cumulated_values_opt1[1]} will expand to value2.
  • cumulativeset
    Exactly like cumulative, except only uniq values are kept.
    e.g: for a script with an opt1 option declared this way:
    argsparse_use_option opt1 "some description" cumulativeset
    and invoked with:
    --opt1 value1 --opt1 value2 --opt1 value1
    after argsparse_parse_options(), "${cumulated_values_opt1[0]}" will expand to value1, and "${cumulated_values_opt1[1]}" will expand to value2. There would be no "${cumulated_values_opt1[2]}" value.
  • "require:<option> <option>"
    Creates a dependency between options. if you declare an option with:
    argsparse_use_option opt1 "something" require:"opt2 opt3"
    argsparse_parse_options() would return with an error if "--opt1" is given on the commande line without "--opt2" or without "--opt3".
You can test if an option has a property using the argsparse_has_option_property() function.
argsparse_has_option_property(option, property)
Determine if an option has a property.
Definition argsparse.sh:685
Parsing positionnal parameters
After the options are declared, invoke the function argsparse_parse_options() with the all script parameters. This will define:
  • program_params, an array, containing all non-option parameters.
  • program_options, an associative array. For each record of the array:
    • The key is the long option name.
    • And about values:
      • If option doesn't expect a value on the command line, the value represents how many times the option has been found on the command line
      • If option does require a value, the array record value is the value of the last occurence of the option found on the command line.
    • If option is cumulative (or cumulativeset), the array record value is the number of values passed by the user.
    After argsparse_parse_options() invokation, you can check if an option have was on the command line (or not) using the argsparse_is_option_set() function.
    e.g:
    argsparse_is_option_set "long-option-name"
    argsparse_is_option_set(option)
    Return True if an option has been set on the command line.
    Definition argsparse.sh:1889
The "usage()" function
If a 'usage' function is defined, and shall argsparse_parse_options() return with non-zero status, 'usage' will be automatically called.
Note
This library automatically defines a default 'usage' function, which may be removed or overridden by the sourcing program afterwards.
Value setting internal logic
During option parsing, for every option of the form '–optionname' expecting a value:
  • If there exists an array named "option_<optionname>_values" and the user-given value doesn't belong to that array, then the argsparse_parse_options() function immediately returns with non-zero status, triggering 'usage'.
  • If the "option_<optionname>_values" array does not exist, but if the option has a type property field, then the value format will be checked against that type.
  • If a function named "check_value_of_<optionname>" has been defined, it will be called with the user-given value as its first positionnal parameter. If check_value_of_<optionname> returns with non-zero status, then parse_option immediately returns with non-zero status, triggering the 'usage' function.
Also, still during option parsing and for every option of the form "--optionname":
  • After value-checking, if a function named "set_option_<optionname>" exists, then, instead of directly modifying the "program_options" associative array, this function is automatically called with 'optionname' as its first positionnal parameter, and, if 'optionname' expected a value, the value is given as the function second positionnal parameter.
About functions return values...

All argsparse functions will return with an error (usually a return code of 1) if called with a wrong number of parameters, and return with 0 if everything went fine.

Function Documentation

◆ __argsparse_parse_options_env_and_defaults()

__argsparse_parse_options_env_and_defaults ( )

set options from environment and from default values.

For every option that have not been set from command line, look for a matching environment variable (when argsparse_are_environment_variables_enabled() is true) and apply default values right after if still left unset.

◆ argsparse_is_option_set()

argsparse_is_option_set ( option )

Return True if an option has been set on the command line.

Parameters
optionan option name.
Return values
0if given option has been set on the command line.

◆ argsparse_option_description()

argsparse_option_description ( option )

Prints to stdout the description of given option.

Parameters
optionan option name.
Return values
0if given option has been previously declared.

◆ argsparse_option_environment_variable()

argsparse_option_environment_variable ( option )

Give the content of the environment variable that can be used to set a given option.

Does not check if option setting through environment variable is enabled or not.

Parameters
optionAn option name
Returns
The content of the environment variable that matches the given option.
Return values
0if the variable that matches the given option actually exists (even if its value is empty)

◆ argsparse_option_environment_variable_name()

argsparse_option_environment_variable_name ( option )

Give the environment variable name linked to an option.

0 Return the name of the environment variable name that can be used to set a given option. Works whether option setting through environment variables is enabled or not.

Parameters
optionan option name
Returns
the environment variable name linked to the option

Return the name of the environment variable name that can be used to set a given option. Works whether option setting through environment variables is enabled or not.

Parameters
optionan option name
Returns
the environment variable name linked to the option

◆ argsparse_parse_options()

argsparse_parse_options ( parameters... )

Parse program options.

This function will make option parsing happen, and if an error is detected, the usage() function will be invoked, if it has been defined. If it's not defined, the function will return 1. Parse options, and return if everything went fine.

Parameters
parameters...should be the program arguments.
Return values
0if the whole option parsing process went fine.
1if an error is encoutered and usage does not perform an exit.

◆ argsparse_report()

argsparse_report ( option... )

Prints a basic report of all passed options.

Kinda useful for a –debug, or a –verbose option, this function will print options and their values.

Parameters
option...A list of option name. If omitted all options will be displayed.
Return values
0

◆ argsparse_set_option_from_environment_value()

argsparse_set_option_from_environment_value ( option ,
value  )

Give a value to an option, from environment variable value.

Options can be set from environment variables, and in some cases, those values have special meanings:

  • 0, "false", "no" and the empty string are explicit values to disable a non-valued option
  • (probably more to come)
Parameters
optionan option name
valuethe value, as found in the process environment, to set the option to.

◆ argsparse_short_to_long()

argsparse_short_to_long ( char )
Parameters
chara short option letter
Returns
if found, the long option name matching given short option letter.

◆ argsparse_use_option()

argsparse_use_option ( optstring ,
description ,
property...  )

Define a new option.

Parameters
optstringan optstring.
descriptionthe option description, for the usage() function.
property...an non-ordered list of keywords. Recognized property keywords are:
  • mandatory: missing option will trigger usage. If a default value is given, the option is considered as if provided on the command line.
  • hidden: option wont show in default usage function.
  • value: option expects a following value.
  • short:c: option has a single-lettered (c) equivalent.
  • exclude:"option1 [ option2 ... ]" option is not compatible with other options option1, option2...
  • cumulative
  • cumulativeset
  • type:sometype
  • The last non-keyword parameter will be considered as the default value for the option. All other parameters and values will be ignored. - might be broken / obsolete and broken
Return values
0if no error is encountered.
2if option name is bad (a message will be printed)
3if option name conflicts with another option (a message will be printed)
4if a wrong property name is provided. (a message will be printed)

Variable Documentation

◆ __argsparse_tmp_identifiers

String AssociativeArray __argsparse_tmp_identifiers

Internal use.

Used to verify declared options do not conflict. Is unset after argsparse_parse_options() being called.

◆ argsparse_pgm

ReadOnly String argsparse_pgm

The name of the program currently using argsparse.

Automatically set by argsparse at load time, it contains the basename (path-less but with extension, if any) of the main script. Used internally to print error messages and by usage-related functions, but can be used by the loading script.

◆ program_options

String AssociativeArray program_options

Options values.

After argsparse_parse_options(), it will contain (if no hook is set for "optionname")

  • "optionname" -> "value", if "optionname" accepts a value.
  • "optionname" -> "how many times the option has been detected on . the command line", else.

◆ program_params

String Array program_params

Positionnal parameters of the script.

After argsparse_parse_options(), it will contain all non-option parameters. (Typically, everything found after the '–')