Check if a variable exists in a list in Bash

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

    If the list is fixed in the script, I like the following the best:

    validate() {
        grep -F -q -x "$1" <

    Then use validate "$x" to test if $x is allowed.

    If you want a one-liner, and don't care about whitespace in item names, you can use this (notice -w instead of -x):

    validate() { echo "11 22 33" | grep -F -q -w "$1"; }
    

    Notes:

    • This is POSIX sh compliant.
    • validate does not accept substrings (remove the -x option to grep if you want that).
    • validate interprets its argument as a fixed string, not a regular expression (remove the -F option to grep if you want that).

    Sample code to exercise the function:

    for x in "item 1" "item2" "item 3" "3" "*"; do
        echo -n "'$x' is "
        validate "$x" && echo "valid" || echo "invalid"
    done
    

提交回复
热议问题