[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Irregularities when using -v, -z, -n

From: Greg Wooledge
Subject: Re: Irregularities when using -v, -z, -n
Date: Thu, 29 Jul 2021 09:42:51 -0400

On Thu, Jul 29, 2021 at 01:21:02PM +0000, Leonid Isaev (ifax) wrote:
> On Thu, Jul 29, 2021 at 03:04:49PM +0200, wrote:
> > How does manual never give examples of how to use things !
> > 6.4 Bash Conditional Expressions
> You are welcome to submit documentation improvements...

Inflating the bash(1) man page even further with thousands of examples
is not likely to be accepted.

The man page is primarily a reference, not a tutorial.  The correct
place for basic examples is in a tutorial or guide.  There are many of

Unraveling things a bit, most of the OP's troubles would go away if
they would simply initialize their variables with default values up
front, instead of trying to determine retroactively whether they
already assigned a value to the variable during option processing.

I thought they had learned this already under the lisa-asket persona,
but I couldn't find the specific message.  There were far too many
to comb through.

All of these questions -- -v, -z, -n, is a variable already set, what
if it's an array, what if... -- all of these are symptoms of the
fundamental problem that they're doing things backwards.

f() {
    local a=0 b=0 file=

    local OPTIND=1 OPTARG opt
    while getopts abf: opt; do
        case $opt in
            a) a=1;;
            b) b=1;;
            f) file=$OPTARG;;
            *) printf 'usage: f [-ab] [-f file]\n' >&2; return 1;;
    shift "$((OPTIND-1))"

    printf 'After doing options, a=<%s> b=<%s> file=<%s>\n' "$a" "$b" "$file"
    printf 'Remaining arguments:'
    (($#)) && printf ' <%s>' "$@"

The local variables a, b and file are initialized with default values
before the option processing starts.  Therefore, there is no need to
check whether they're "set" after the loop has finished.  They're always
set to something, either a default value, or a different value, depending
on which options are given to the function.

All one needs to do after that is look at the *values* of the variables,
and do whatever is appropriate for this function.

reply via email to

[Prev in Thread] Current Thread [Next in Thread]