1

Is there possibility to parse obligatory argument containing colon using getopt in bash?

Let's say I've prepared code like below:

    while getopts "qt:i:" arg; do
        case "$arg" in
             :)
                HOST=$(printf "%s\n" "$1"| cut -d : -f 1)
                PORT=$(printf "%s\n" "$1"| cut -d : -f 2)
                shift 1
                ;;
            -q)
                QUIET=1
                shift 1
                ;;
            -t)
                TIMEOUT="$2"
                if [ "$TIMEOUT" = "" ]; then break; fi
                shift 2
                ;;
            -i)
                INTERVAL="$2"
                if [ "$INTERVAL" = "" ]; then break; fi
                shift 2
                ;;
            -h)
                usage 0
                ;;
            *)
                echoerr "Unknown argument: $1"
                usage 1
                ;;
        esac
    done

Full code can be found here: https://pastebin.com/1eFsG8Qn

How i call the script:

wait-for database:3306 -t 60 -i 10

Problem is that this logic can't parse HOST_URL:PORT. Any tips how to parse it?

Mateusz
  • 219
  • 2
  • 13
  • That's a colon, not a semicolon. The problem is that `getopts` stops parsing as soon as it finds something that doesn't start with a `-`. – chepner Jul 18 '21 at 20:48
  • Thanks for catching naming mistake:) Does it mean that `getopts` will not work in that case? – Mateusz Jul 18 '21 at 20:51
  • Yes; if you want to allow positional arguments to precede options, you'll need to use something else (like GNU `getopt`), or parse the arguments yourself. – chepner Jul 18 '21 at 21:20

1 Answers1

0

Is there possibility to parse obligatory argument containing colon using getopt in bash?

Sure - they have to be after options.

wait-for -t 60 -i 10 database:3306

then:

while getopts .... ;do
    case ...
    blabla) .... ;;
    esac
done
shift "$(($OPTIND-1))"
printf "Connect to %s\n" "$1"      # here

The colon in argument is not anyhow relevant.

Any tips how to parse it?

Use getopt - it reorders the arguments.

KamilCuk
  • 120,984
  • 8
  • 59
  • 111