Check if a variable exists in a list in Bash

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

    [[ $list =~ (^|[[:space:]])$x($|[[:space:]]) ]] && echo 'yes' || echo 'no'
    

    or create a function:

    contains() {
        [[ $1 =~ (^|[[:space:]])$2($|[[:space:]]) ]] && exit(0) || exit(1)
    }
    

    to use it:

    contains aList anItem
    echo $? # 0: match, 1: failed
    

提交回复
热议问题