Command Line Interface

Author: Adrian Perez <aperez@igalia.com>
Copyright: 2008-2009 Igalia S.L.
License:GPL3

Abstract

User interaction using a command, line-oriented interface.

Contents

cli_optparse

cli_optparse [ -h ] [ -n ] options destination

Parses command line options. Supports both short and long options, as well as specifying defaults for options and generating help messages. Valid options, default values and descriptive texts for them are specified as an array of 3-tuples of the following:

The destination parameter should be a hash table in which values for options will be stored. Make sure it is initialized before calling this function.

As an example:

opts=(
    q:quiet  false    'Quiet operation'
    i:input  ''       'Takes one argument'
    u:user   "$USER"  'User name'
)

The previous array defines options which allow all of the following possibilities (among others):

--quiet
-q --input input-file
-u john --quiet -i foo

If the -h switch is given, a help message is generated when unrecognized command line options are found, and the process will exit with a non-zero status. If not given, the help message is not printed, but the function will have a non-zero exit status.

Command line will be parsed until the first non-option is found. The CLI_LAST_ARG variable will be set to the index of the last proper option.

cli_qa_batch

cli_qa_batch [ -f | --force-ask ] values questions

Performs a series of interactive questions, asking the user for answers and gathering answers into a hash table. Question sets are arrays of 3-tuples with the following components:

As en example, the following could be used to input an user's information:

questions=(
    username  'User name'  "$USER"
    firstname 'First name' ''
    lastname  'Last name'  ''
)
values=$(hash_new)
cli_qa_batch $values questions
echo "Hello Mr. $(hash_get $values lastname)"

The above code would result in an interactive session like the following, supposing your login name is john:

User name [john] > ripper
First name > John
Last name > T. Ripper
Hello Mr. T. Ripper!

As you can see, default values are suggested between brackets, like in the first question of the example, and if the user just taps the “enter” key the default value will be used as input.

When requested values already have a key in the values hash table its value will be used instead of asking the user. If you pass the -f (also --force-ask) flag the user will be prompted with the value stored in the hash table as suggestion.