switch case in bash

Asked

Viewed 201 times

2

Man switch case is not working properly:

while getopts "hvo:umsf" OPTION
do
    case $OPTION in
        i) instalarSniper
        ;;
        h) help
        ;;
        s) simular
        ;;
        d) adicionais
        ;;
        ?) echo "Parametros incorretos, digite -h para ajuda"
        ;;
    esac
done

More specifically, my parameters -h and -s are working, but if I try -i or -d, it goes to the case of incorrect parameters.

Someone would know to tell me what’s wrong?

2 answers

1

In the getopts you must pass the options that are accepted. As it does not have the letter i, it will not be recognized. Putting only the options that are in the case, gets like this:

while getopts "hisd" OPTION
do
    case $OPTION in
        i) instalarSniper
        ;;
        h) help
        ;;
        s) simular
        ;;
        d) adicionais
        ;;
        ?) echo "Parametros incorretos, digite -h para ajuda"
        ;;
    esac
done

Thus, the accepted parameters are -h, -i, -s and -d.

If you want more complex options, see tutorial of getopts.

0

The @hkotsubo response looks great, together only the typical structure of a script bash with options and parameters, according to my personal tastes:

#!/bin/bash

while getopts "hi:" OPT        ## processar opções
do
    case $OPT in
        i) iv=$OPTARG ; echo instalar $iv;;
        h) echo help           ; exit 0 ;;
       \?) echo "usage: $0 ..."; exit 1 ;;
    esac
done

shift $((OPTIND-1))            ## avançar até argumentos

for a in "$@"                  ## processar argumento
do
  echo "=== processar '$a'==="
done

Browser other questions tagged

You are not signed in. Login or sign up in order to post.