Check if a variable exists in a list in Bash

后端 未结 17 548
囚心锁ツ
囚心锁ツ 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-29 17:53

    An alternative solution inspired by the accepted response, but that uses an inverted logic:

    MODE="${1}"
    
    echo "<${MODE}>"
    [[ "${MODE}" =~ ^(preview|live|both)$ ]] && echo "OK" || echo "Uh?"
    

    Here, the input ($MODE) must be one of the options in the regular expression ('preview', 'live', or 'both'), contrary to matching the whole options list to the user input. Of course, you do not expect the regular expression to change.

提交回复
热议问题