简体   繁体   中英

Usage function with output level numbers

I am using the following code. My intention is to print some usage information depending on the value associated with -u .

For instance, if I have the invocation heading -u1 and heading -u2 , I get the correct information being displayed using the case conditions (1) and (2) .

But I am encountering a problem when using just heading -u . In such a situation I want to print the heading usage that appears when $# == 0 . I noticed that when calling heading -u , the function heading_usage has $1 empty, but $# is 1 .

heading_usage ()
{
 printf '%s\n' "heading_usage .$*. $#"
 if (( $# == 0 )); then
   printf '%s\n' "  heading [OPTIONS] HEADING"
 fi

 case $1 in
  (1)
    printf '%s\n' " Some Information"
    ;;
  (2)
    printf '%s\n' "Additional Information"
    ;;
 esac
}

heading ()
{ 
 while (( $# > 0 )); do
  case $1 in
   ("-u"|"--usage")
     usg="$2" ; shift ; shift
     heading_usage "$usg"
     return 0
     ;;
   ("-u="*|"--usage="*)
     usg="${1#*=}" ; shift 1
     heading_usage "$usg"
     return 0
     ;;
   ("-u"*)
     usg="$2" ; shift ; shift
     printf '%s\n' "usg: .$usg."
     heading_usage "$usg"
  esac
 done
}
 ("-u"*)
    usg="$2" ; shift ; shift

That's not $2 - it's one argument, -u , and it's in $1 , and it's one argument so don't shift;shift but only one shift .

 "-u"*)
    usg="${1#-u}" ; shift

Don't reinvent the wheel - strongly consider using getopts (portable options, but only short options) or GNU getopt (non-portable option, Linux specific, but supports long and optional options).

In such a situation I want to print the heading usage that appears when $# == 0

As pointed by You, it looks like "-u" picks up the case. So check there is there exists the next argument:

-u|--usage)
     if (($# > 1)); then
        usg="$2"
        heading_usage "$usg"
     else
        heading_usage
     fi
     return 0
     ;;;
 "-u"*)
    usg="${1#-u}"
    shift
    ...
    ;;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM