Check if a variable exists in a list in Bash

后端 未结 17 556
囚心锁ツ
囚心锁ツ 2020-11-29 17:08

I am trying to write a script in bash that check the validity of a user input.
I want to match the input (say variable x) to a list of valid values.

<
17条回答
  •  天涯浪人
    2020-11-29 17:44

    This is almost your original proposal but almost a 1-liner. Not that complicated as other valid answers, and not so depending on bash versions (can work with old bashes).

    OK=0 ; MP_FLAVOURS="vanilla lemon hazelnut straciatella"
    for FLAV in $MP_FLAVOURS ; do [ $FLAV == $FLAVOR ] && { OK=1 ; break; } ; done
    [ $OK -eq 0 ] && { echo "$FLAVOR not a valid value ($MP_FLAVOURS)" ; exit 1 ; }
    

    I guess my proposal can still be improved, both in length and style.

提交回复
热议问题