Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 52 additions & 16 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,44 +1,78 @@
#Optparse
A BASH wrapper for getopts, for simple command-line argument parsing
A BASH wrapper for getopts and compgen, for simple command-line argument parsing an bash completion.

##What is this?
A wrapper that provides a clean and easy way to parse arguments to your BASH scripts. It lets you define short and long option names, handle flag variables, and set default values for optional arguments, all while aiming to be as minimal as possible: *One line per argument definition*.
A wrapper that provides a clean and easy way to parse arguments and create Tab completion to your BASH scripts. It lets you define short and long option names, handle flag variables, set default values for optional arguments and an optional list of posible values for options to complete, all while aiming to be as minimal as possible: *One line per argument definition*.

##Usage
##### See `sample_head.sh` for a demonstration of optparse
###1. Define your arguments
###1. Install bash-completion package.
###2. Create a script to generate completion and option parsing files.
###3. Source file optparse.bash in the script.
###4. Define your arguments in the script.

Each argument to the script is defined with `optparse.define`, which specifies the option names, a short description, the variable it sets and the default value (if any).
Each argument to the script is defined with `optparse.define`, which specifies the option names, a short description, the variable it sets, the default value (if any) and a list of posible values (if any).

```bash
optparse.define short=f long=file desc="The input file" variable=filename
optparse.define short=n long=name desc="The event name" variable=name
```

Flags are defined in exactly the same way, but with an extra parameter `value` that is assigned to the variable.

```bash
optparse.define short=v long=verbose desc="Set flag for verbose mode" variable=verbose_mode value=true default=false
```
optparse.define short=c long=country desc="The event country" variable=country list="USA Canada Japan Brasil England"
```

```bash
optparse.define short=y long=year desc="The event year" variable=year list="2006 2010 2014 2020"
```

Another way to pass a completion list is to assign a command output to list variable as follow.

```bash
optparse.define short=y long=year desc="The event year" variable=year list="\$(my_command)"
```

###2. Evaluate your arguments
The `optparse.build` function creates a temporary header script based on the provided argument definitions. Simply source the file the function returns, to parse the arguments.
###5. Evaluate your arguments
The `optparse.build` function creates a header script and a configuration file in $HOME/.bash_completion.d/ based on the provided argument definitions.

```bash
source $( optparse.build )
optparse.build script_name
```

###5. Allow execution to the script and execute it.
##### See `sample_event_generate_completion.sh` for a demonstration.
###6. Source profile bash completion configuration, example:
```bash
$ source $HOME/.bash_completion.d/*
```

###7. In your command script( The script to parse arguments and generate completion ) source the optparse generated file to parse and evaluate arguments.

####That's it!
The script can now make use of the variables. Running the script (without any arguments) should give you a neat usage description.
The script can now show completion and make use of the variables. Running the script (without any arguments) should give you a neat usage description.

usage: ./script.sh [OPTIONS]

OPTIONS:

-f --file : The input file
-v --verbose : Set flag for verbose mode
-n --name : The event name
-c --country : The country name
-y --year : The year

-? --help : usage


##### See `sample_event.sh` for a demonstration.
### Now to use the command script we can write:
```bash
$ ./sample_event.sh [TAB][TAB]
$ --name --country --year
$ ./sample_event.sh --country [TAB][TAB]
$ USA Canada Japan Brasil
$ ./sample_event.sh --name "Football World Cup" --country Brasil --year 2014
$ The Football World Cup will be in Brasil in 2014.
```


##Supported definition parameters
All definition parameters for `optparse.define` are provided as `key=value` pairs, seperated by an `=` sign.
####`short`
Expand All @@ -53,13 +87,15 @@ the value to set the variable to. If unspecified, user is expected to provide a
a short description of the argument (to build the usage description)
####`default`(optional)
the default value to set the variable to if argument not specified
####`list`(optional)
the list of posible arguments for an option to autocomplete. It could be a list of strings or a command.

##Installation
1. Download/clone `optparse.bash`
2. Add

```bash
`source /path/to/optparse.bash`
source /path/to/optparse.bash
```
to `~/.bashrc`

49 changes: 43 additions & 6 deletions optparse.bash
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
# Optparse - a BASH wrapper for getopts
# Optparse - a BASH wrapper for getoptions
# @author : nk412 / nagarjuna.412@gmail.com

optparse_usage=""
optparse_contractions=""
optparse_defaults=""
optparse_process=""
optparse_arguments_string=""
optparse_process_completion=""
options=""

# -----------------------------------------------------------------------------------------------------------------------------
function optparse.throw_error(){
Expand Down Expand Up @@ -45,6 +47,8 @@ function optparse.define(){
local variable="$value"
elif [ "$key" = "value" ]; then
local val="$value"
elif [ "$key" = "list" ]; then
local list="$value"
fi
done

Expand All @@ -57,7 +61,7 @@ function optparse.define(){
fi

# build OPTIONS and help
optparse_usage="${optparse_usage}#NL#TB${short} $(rpad "$long:" 25) ${desc}"
optparse_usage="${optparse_usage}#NL#TB${short} $(printf "%-25s %s" "${long}:" "${desc}")"
if [ "$default" != "" ]; then
optparse_usage="${optparse_usage} [default:$default]"
fi
Expand All @@ -70,11 +74,22 @@ function optparse.define(){
optparse_arguments_string="${optparse_arguments_string}:"
fi
optparse_process="${optparse_process}#NL#TB#TB${shortname})#NL#TB#TB#TB${variable}=\"$val\";;"

# Complete options
options="${options} ${long}"
# Complete command arguments
if [ "$list" != "" ]; then
optparse_process_completion="${optparse_process_completion}#NL#TB#TB--${variable})#NL#TB#TB#TB${variable}_list=\"$list\"#NL#TB#TB#TBCOMPREPLY=( \$(compgen -W \"\${${variable}_list}\" -- \${cur}) )#NL#TB#TB#TBreturn 0;;"
fi

}

# -----------------------------------------------------------------------------------------------------------------------------
function optparse.build(){
local build_file="/tmp/optparse-${RANDOM}.tmp"
local script=${1:?}
local build_file="${script}_optparse"
local completion_dir="$HOME/.bash_completion.d/"
local completion_file="${completion_dir}${script}"

# Building getopts header here

Expand Down Expand Up @@ -132,12 +147,36 @@ while getopts "$optparse_arguments_string" option; do
esac
done

EOF

# Create completion script
mkdir -p $completion_dir
cat << EOF > $completion_file
_$script(){
local cur prev options
COMPREPLY=()
cur=\${COMP_WORDS[COMP_CWORD]}
prev=\${COMP_WORDS[COMP_CWORD-1]}

# The basic options we'll complete.
options="${options}"

# Complete the arguments to some of the basic commands.
case \$prev in
$optparse_process_completion
*)
esac
COMPREPLY=(\$(compgen -W "\${options}" -- \${cur}))
return 0
}
complete -F _$script $script
EOF

local -A o=( ['#NL']='\n' ['#TB']='\t' )

for i in "${!o[@]}"; do
sed -i "s/${i}/${o[$i]}/g" $build_file
sed -i "s/${i}/${o[$i]}/g" $completion_file
done

# Unset global variables
Expand All @@ -146,8 +185,6 @@ EOF
unset optparse_arguments_string
unset optparse_defaults
unset optparse_contractions

# Return file name to parent
echo "$build_file"
unset options
}
# -----------------------------------------------------------------------------------------------------------------------------
14 changes: 14 additions & 0 deletions sample_event.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
#!/bin/bash

# Source the sample_event_optparse file ---------------------------------------------------
source sample_event.sh_optparse

if [ -z "$name" ] || [ -z "$country" ] || [ -z "$year" ]; then
usage; exit 1
fi

# Display event information
echo "The $name event will be in $country in $year."

exit 0

15 changes: 15 additions & 0 deletions sample_event_generate_completion.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
#!/bin/bash

# Source the optparse.bash file ---------------------------------------------------
source optparse.bash

# Define options
optparse.define short=n long=name desc="The event name" variable=name
optparse.define short=c long=country desc="The event country" variable=country list="USA Canada Japan Brasil England"
optparse.define short=y long=year desc="The event year" variable=year list="2006 2010 2014 2020"

# Generate optparse and autocompletion scripts
script_name="sample_event.sh"
optparse.build $script_name

exit 0