kward / shflags

shFlags is a port of the Google gflags library for Unix shell.
Apache License 2.0
283 stars 45 forks source link

When parsing a command line is a part of a "main" function, the library doesn't work #19

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
What steps will reproduce the problem?
# source shflags
. ./shflags-1.0.3/src/shflags

# define a 'name' command-line string flag
DEFINE_string 'name' 'world' 'name to say hello to' 'n'

function main ()
{
 # parse the command-line
 FLAGS "$@" || exit 1
 eval set -- "${FLAGS_ARGV}"

 echo "Hello, ${FLAGS_name}!"
}

main

What is the expected output? What do you see instead?

What version of the product are you using? On what operating system?
shflags-1.0.3

Please provide any additional information below.
when parsing the command line is out of main function, everything is fine

Original issue reported on code.google.com by milan.m....@gmail.com on 17 Apr 2012 at 11:47

GoogleCodeExporter commented 9 years ago
The reason your example does not work is that within the scope of main(), $@ 
represents the arguments passed to the main() function.  If you replace the 
final with:

main $@

then it should work correctly.  I don't think this represents a defect in the 
shflags library.

Original comment by ben...@gmail.com on 28 May 2012 at 4:36

GoogleCodeExporter commented 9 years ago
benley is correct as to the reason. I'd suggest putting double-quotes around 
the $@ for the main call. I've found through experience that gives the best 
results across a wider range of shells.

main "$@"

The way I personally do this is more like below. The main is never called 
unless the FLAGS parsing happened correctly, and the only thing passed into 
main() are the non-flag arguments, making the $#, $* and $@ variables useful as 
you'd expect them.

main()
{
  echo "${FLAGS_some_flag}"
}

FLAGS "$@" || exit $?
eval set -- "${FLAGS_ARGV}"
main "$@"

Original comment by kate.w...@forestent.com on 6 Jan 2013 at 4:49

GoogleCodeExporter commented 9 years ago
Thanks for educating me, guys. I appreciate it.
Cheers.

Original comment by milan.m....@gmail.com on 6 Jan 2013 at 6:47