Check if a variable exists in a list in Bash

后端 未结 17 503
囚心锁ツ
囚心锁ツ 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:33

    If your list of values is to be hard-coded in the script, it's fairly simple to test using case. Here's a short example, which you can adapt to your requirements:

    for item in $list
    do
        case "$x" in
          item1|item2)
            echo "In the list"
            ;;
          not_an_item)
            echo "Error" >&2
            exit 1
            ;;
        esac
    done
    

    If the list is an array variable at runtime, one of the other answers is probably a better fit.

提交回复
热议问题