0

Let's say this is my script:

#!/bin/sh

# source shflags
. shflags

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

# parse the command-line
FLAGS "$@" || exit $?
eval set -- "${FLAGS_ARGV}"

# say Hello!
echo "Hello, ${FLAGS_name}!"

For using --help (or -h) I can see the usage/help:

USAGE: ./sample.sh [flags] args
flags:
  -n,--name:  name to say hello to (default: 'world')
  -h,--[no]help:  show this help (default: false)

However I'd like to display the same usage/help (shflags constructed) also in case of no arguments provided to script. Any idea how can I do so?

I've tried adding:

if [ $# == 0 ] ; then
    echo $USAGE
    exit 1;
fi

Well, the detection of no args works, but I have nothing printed.

UPDATE:

shflags version refered is available on: http://code.google.com/p/shflags/source/browse/tags/1.0.3/src/shflags

4

1 回答 1

2

好的,明白了,以下为我完成了这项工作:

#!/bin/sh

# source shflags
. shflags

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

# parse the command-line
FLAGS "$@" || exit $?
if [ $# == 0 ] ; then
    flags_help
    exit 1;
fi
eval set -- "${FLAGS_ARGV}"

# say Hello!
echo "Hello, ${FLAGS_name}!"

感谢@Ansgar.Wiechers 在询问 shflags 的来源时为我指出了正确的方向:) 我自己在那里找到了它:)

所以感兴趣的函数是:

flags_help
于 2013-07-08T08:14:52.053 回答