Check if a variable exists in a list in Bash

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

    Thought I'd add my solution to the list.

    # Checks if element "$1" is in array "$2"
    # @NOTE:
    #   Be sure that array is passed in the form:
    #       "${ARR[@]}"
    elementIn () {
        # shopt -s nocasematch # Can be useful to disable case-matching
        local e
        for e in "${@:2}"; do [[ "$e" == "$1" ]] && return 0; done
        return 1
    }
    
    # Usage:
    list=(11 22 33)
    item=22
    
    if elementIn "$item" "${list[@]}"; then
        echo TRUE;
    else
        echo FALSE
    fi
    # TRUE
    
    item=44
    elementIn $item "${list[@]}" && echo TRUE || echo FALSE
    # FALSE
    

提交回复
热议问题