Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Script breaks when using bash's nounset option #15

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

erikvip
Copy link

@erikvip erikvip commented Jun 4, 2016

Optparse breaks when set -o nounset is enabled. This option makes bash generate an error when an uninitialized variable is encountered. Having this option on is generally good practice, kinda like strict mode, and is easy to fix.

Example code

Create an option with no default, turn on set -o nounset, and don't specify a value for argument.

#!/usr/bin/env bash
set -o nounset
source "optparse.bash"
optparse.define short=i long=input desc="The input file. No default" variable=INPUT value=""
source $(optparse.build);

Now run the script with no arguments:

$ ./test.sh
optparse.bash: line 77: default: unbound variable

Expected Result

Should not throw an error

Cause

Local variables in the optparse.build parser loop are not declared. So since no 'default' attribute was given in optparse.define, it's uninitialized when we check for it later.

Also when generating $optparse_defaults, arguments with no default specified should be declared empty.

Fix

Easy fix, just initialize all the local variables in optparse.define, prior to the parsing loop. Also in $optparse_defaults, when $default is empty, declare an empty variable.

Above for loop

+
+ # Initialize all local variables. This is needed for set -o nounset
+ local short="" shortname="" long="" longname="" desc="" default="" variable="" val="";
+
  for option_id in $( seq 1 $# ) ; do

While generating $optparse_defaults

  if [ "$default" != "" ]; then
    optparse_defaults="${optparse_defaults}#NL${variable}=${default}"
+ else
+   optparse_defaults="${optparse_defaults}#NL${variable}=\"\""

Final Thoughts

I've got a pull request coming your way to fix this too.

This is a really easy bug fix for an issue that violates best practices for bash scripting. I hope you'll accept it in a timely manner. Thanks.

…n if they're not specified and don't have a default
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant