Check if a variable exists in a list in Bash

后端 未结 17 549
囚心锁ツ
囚心锁ツ 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
    2020-11-29 17:46

    Matvey is right, but you should quote $x and consider any kind of "spaces" (e.g. new line) with

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

    so, i.e.

    # list_include_item "10 11 12" "2"
    function list_include_item {
      local list="$1"
      local item="$2"
      if [[ $list =~ (^|[[:space:]])"$item"($|[[:space:]]) ]] ; then
        # yes, list include item
        result=0
      else
        result=1
      fi
      return $result
    }
    

    end then

    `list_include_item "10 11 12" "12"`  && echo "yes" || echo "no"
    

    or

    if `list_include_item "10 11 12" "1"` ; then
      echo "yes"
    else 
      echo "no"
    fi
    

    Note that you must use "" in case of variables:

    `list_include_item "$my_list" "$my_item"`  && echo "yes" || echo "no"
    

提交回复
热议问题