Skip to end of metadata
Go to start of metadata

A new functionality has recently been added to bash-related comma utilities that allows specifying default values of command line options where the options are defined. 

The following code uses command line option --filename. The script defines a bash variable called filename, whose value is specified by the option on the command line. However, if the option is not given on the command line, the default value will be used. 

#!/bin/bash
 
function options_description
{
    cat <<END
--filename=[<filename>]; default=example.txt; example file
END
}
 
source $( type -p comma-application-util )
eval "$( options_description | comma-options-to-name-value "$@" | comma_path_value_mangle )"
 
echo "filename is $filename"

Save the code above in a file called script and make it runnable with 'chmod +x ./script'. Then execute the following commands:

$ ./script
filename is example.txt
$ ./script --filename another.txt
filename is another.txt

The first command uses the default value (example.txt), while the second command uses the given value (another.txt).

The default values can be enclosed in double or single quotes if necessary. For instance:

function options_description
{
    cat <<END
--command=[<command>]; default="cat /log/file"; command to execute
END
}
  • No labels