optparse
optparse copied to clipboard
#NL assoc array key assignment throwing syntax error
Cloning the repo and running $ bash sample_head.sh --help
produces the following output, including a syntax error:
$ bash sample_head.sh --help
optparse.bash: line 140: #NL: syntax error: operand expected (error token is "#NL")
sample_head.sh: line 11: source: filename argument required
source: usage: source filename [arguments]
ERROR: Please provide a file
Looks like this associative array assignment is throwing the error:
local -A o=( ['#NL']='\n' ['#TB']='\t' )
Running the following BASH version:
$ bash --version
GNU bash, version 3.2.51(1)-release (x86_64-apple-darwin13)
Copyright (C) 2007 Free Software Foundation, Inc.
Any idea how to fix this? My bash foo is pretty weak.
I see the use of #NL
and #TB
as placeholders for newlines and tabs (respectively), which are replaced on the lines following that assignment. It looks like the use of #
as a special character is the reason for the ['#NL']
syntax in the array declaration. Not really sure how that works or how to debug this.
Same bug here. The bash script using optparse works perfectly on Linux, but it throws this error on OSX.
Well, I investigate and there are two issues actually.
First one, on OSX Mavericks, the bash version is 3.7 (released in 2007!). That's very old! Associative array's are supported since Bash 4+. So I advise you to update your bash by following this guide
Second problem, sed
doesn't behaves the same way on Mavericks and on Linux. Maybe a problem of version. That causes #NL
to be replaced by n
instead of newline. It exists solution like describe in this thread on SO.
But it seems to do not work for #TB
.
Anyway, I fixed the bug by replacing sed
with perl
.
The line which replaces #NL
and #TB
become:
perl -i -pe "s/${i}/${o[$i]}/g" $build_file
Generally, I think perl
is more suitable to this kind of job. sed
is good for simple inline regex, but it doesn't support complex regex and multiline mode.
BTW, I do not think using perl
makes the script less portable. AFAIK, it is built-in Mavericks (and probably in Yosemite). I do not know about Linux distros, but it is not a big deal to install it.
@nk412 It needs still testing on Linux but I may issue a pull-request if you want. Just let me know.
+1
osx 10.12
I did this: brew install gnu-sed --with-default-names
git cloned this project today
LAPTOP $ echo $BASH_VERSION
4.4.5(1)-release
LAPTOP $ ./run-app2.sh
optparse.bash: line 162: #NL: syntax error: operand expected (error token is "#NL")
./run-app2.sh: line 20: source: filename argument required
source: usage: source filename [arguments]
@jbenoit2011 can you please submit a PR or explain exactly where this code goes in your fix?
@nk412 can this be fixed or worked around so that it works on linux and osx?
For anyone else this seems to simplify it tremendously
sed -i "s/#NL/\n/g" $build_file
sed -i "s/#TB/\t/g" $build_file