Calling a function that uses `getopt` inside another function that uses `getopt`

37 views Asked by At

Consider the following script called mwe.sh:

#!/usr/bin/env bash

o() {
    printf "DEBUG: o: executing...\n"
    printf "DEBUG: o: args: %s\n" "$*"
    local show_ifconfig
    while getopts "i:" opt; do
        case $opt in
        i)
            show_ifconfig="$OPTARG"
            ;;
        \?)
            echo "Invalid option: -$OPTARG" >&2
            ;;
        esac
    done
    printf "DEBUG: o: show_ifconfig: %s\n" "$show_ifconfig"
    if [[ $show_ifconfig == yes ]]; then
        ifconfig
    fi
}

oo () {
    printf "DEBUG: oo: executing...\n"
    printf "DEBUG: oo: args: %s\n" "$*"
    local myvar1
    local myvar2
    while getopts "s:t:" opt; do
        case $opt in
        s)
            myvar1=yes
            ;;
        t)
            myvar2=yes
            ;;
        \?)
            echo "Invalid option: -$OPTARG" >&2
            ;;
        esac
    done
    printf "DEBUG: oo: myvar1: %s\n" "$myvar1"
    o -i yes
}

oo -s yes

When running this, I get:

$ bash mwe.sh; echo $?
DEBUG: oo: executing...
DEBUG: oo: args: -s yes
DEBUG: oo: myvar1: yes
DEBUG: o: executing...
DEBUG: o: args: -i yes
DEBUG: o: show_ifconfig:
0

So it seems that the loop inside the o function is not being executed. Or it is but it iterating over something empty.

Why is that?

0

There are 0 answers