Browse Source

Minor fix for overriding values of optional parameters. Fixed the help command.

dev
Franco Masotti 4 years ago
parent
commit
383490210c
  1. 23
      _posts/2018-11-18-my-bash-option-parsing-template.md

23
_posts/2018-11-18-my-bash-option-parsing-template.md

@ -1,7 +1,7 @@
---
title: My bash template for option parsing
tags: [getopts, bash, template, bashisms, shell]
updated: 2018-11-23 17:00
updated: 2018-11-26 19:40
description: a template for option parsing in Bash based on getopt
---
@ -64,18 +64,18 @@ The template is known to work with the following packages
| Package | Package version | fbopt version |
|---------|-----------------|---------------|
| GNU Bash | `GNU bash, version 4.4.23(1)-release (x86_64-unknown-linux-gnu)` | `0.1`, `0.2` |
| getopt | `getopt from util-linux 2.33` | `0.1`, `0.2` |
| getopt | `getopt from util-linux 2.33` | `0.1`, `0.2`, `0.3` |
## The template
To allow inclusion in any project the template is released under the [CC0 1.0 license](https://creativecommons.org/publicdomain/zero/1.0/legalcode.txt).
What follows is `fbopt` version `0.2`.
What follows is `fbopt` version `0.3`.
```shell
#!/bin/bash
#
# fbopt version 0.2
# fbopt version 0.3
#
# Written in 2018 by Franco Masotti/frnmst <franco.masotti@student.unife.it>
#
@ -94,16 +94,17 @@ What follows is `fbopt` version `0.2`.
show_help()
{
cat <<-EOF
Usage: <program_name> [OPTIONS] ARGUMENT(S)
Usage: <program_name> [OPTION] ARGUMENT
<Description>
Mandatory arguments to long options are mandatory for short options too.
Options:
-a, --flag-a set a
-b, --flag-b set b
-a, --flag-a=FLAGA set a
-b, --flag-b=FLAGB set b
-c enable c
-d enable d
-e, --flag-e set e
-f enable and or set f
-e, --flag-e=FLAGE set e
-f[=FLAGF] enable and or set f
with an optional argument
-h, --help print this help
--print-flags print the enabled options. This can also
@ -154,7 +155,7 @@ main()
local flag_c=''
local flag_d='false'
local flag_e='false'
local flag_f='no'
local flag_f='false'
local program_name="${0}"
opts="$(getopt \
@ -222,6 +223,8 @@ main()
'flag_f' \
&& return 0
[ "${help}" = 'true' ] && show_help && return 0
# Override values of optional parameters.
[ -z "${flag_f}" ] && flag_f='true'
# From now on you should call a function or an external program
# using the values of the flag variables.

Loading…
Cancel
Save