我试图在bash中编写一个脚本,检查用户输入的有效性。 我想将输入(变量x)匹配到一个有效值列表。

我现在想到的是:

for item in $list
do
    if [ "$x" == "$item" ]; then
        echo "In the list"
        exit
    fi
done

我的问题是,如果有更简单的方法, 对于大多数编程语言,类似list.contains(x)。

列表是:

list="11 22 33"

我的代码将只对这些值回显消息,因为list被视为数组而不是字符串, 所有的字符串操作都将验证1,而我希望它失败。


当前回答

如何

echo $list | grep -w -q $x

您可以检查输出或$?上面的线来做决定。

Grep -w检查整个单词模式。添加-q可以防止列表回显。

其他回答

如果你使用双括号,你也可以在case语句外使用(*通配符):

string='My string';

if [[ $string == *My* ]]
then
echo "It's there!";
fi

我想把我的解决方案也加进去。

# 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

下面的脚本实现了一个列表的包含函数。

    function contains {
      local target=$1
      shift
    
      printf '%s\n' "$@" | grep -x -q "$target"
      out=$?
      (( out = 1 - out ))
      return $out
    }

如果将一个基于空白的字符串转换为一个列表并使用它,它似乎可以按以下方式解决。


    list="11 22 33"
    IFS=" " read -ra parsed_list <<< "$list"
    
    # parsed_list would be ("11" "22" "33")
    
    contains "11" "${parsed_list[@]}"
    echo $?  # 1
    
    contains "22" "${parsed_list[@]}"
    echo $?  # 1
    
    contains "1" "${parsed_list[@]}"
    echo $? # 0
    
    contains "11 22" "${parsed_list[@]}"
    echo $? # 0

例子

$ in_list super test me out
NO

$ in_list "super dude" test me out
NO

$ in_list "super dude" test me "super dude"
YES

# How to use in another script
if [ $(in_list $1 OPTION1 OPTION2) == "NO" ]
then
  echo "UNKNOWN type for param 1: Should be OPTION1 or OPTION2"
  exit;
fi

in_list

function show_help()
{
  IT=$(CAT <<EOF

  usage: SEARCH_FOR {ITEM1} {ITEM2} {ITEM3} ...

  e.g. 

  a b c d                    -> NO
  a b a d                    -> YES
  "test me" how "test me"    -> YES

  )
  echo "$IT"
  exit
}

if [ "$1" == "help" ]
then
  show_help
fi

if [ "$#" -eq 0 ]; then
  show_help
fi

SEARCH_FOR=$1
shift;

for ITEM in "$@"
do
  if [ "$SEARCH_FOR" == "$ITEM" ]
  then
    echo "YES"
    exit;
  fi
done

echo "NO"

这几乎是你最初的提议,但几乎是一行。不像其他有效答案那么复杂,也不那么依赖于bash版本(可以使用旧的bash)。

OK=0 ; MP_FLAVOURS="vanilla lemon hazelnut straciatella"
for FLAV in $MP_FLAVOURS ; do [ $FLAV == $FLAVOR ] && { OK=1 ; break; } ; done
[ $OK -eq 0 ] && { echo "$FLAVOR not a valid value ($MP_FLAVOURS)" ; exit 1 ; }

我想我的提案在篇幅和风格上都还可以改进。