Check if a variable exists in a list in Bash

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

    I find it's easier to use the form echo $LIST | xargs -n1 echo | grep $VALUE as illustrated below:

    LIST="ITEM1 ITEM2"
    VALUE="ITEM1"
    if [ -n "`echo $LIST | xargs -n1 echo | grep -e \"^$VALUE`$\" ]; then
        ...
    fi
    

    This works for a space-separated list, but you could adapt it to any other delimiter (like :) by doing the following:

    LIST="ITEM1:ITEM2"
    VALUE="ITEM1"
    if [ -n "`echo $LIST | sed 's|:|\\n|g' | grep -e \"^$VALUE`$\"`" ]; then
       ...
    fi
    

    Note that the " are required for the test to work.

提交回复
热议问题