使用Bash

时间:2015-09-22 22:35:31

标签: arrays bash

我想找到一种比较用户输入和排序数组的最快方法。假设我有一个像这样的数组

$ {arr[@]} = {Adam, Bob, Carl, Daniel}

来自终端的用户输入

$ Emma Carl Bob Frank

我想要一个比较函数,可以打印相同的值,如

$ [ Carl, Bob ] already registerd

这是我当前的脚本,仅适用于1个没有空格的单个输入

containsElement () {
  local e
  for e in "${@:2}"; do [[ "$e" == "$1" ]] && return 1; done
  return 0
}

while true; do
  echo "Enter usernames, seperated by a space: "
  read USERNAMES
  containsElement "$USERNAMES" "${arr[@]}"
  var=$?
  if [ "$var" == '1' ]; then
    echo "User already exists!"
    break
  fi
done

1 个答案:

答案 0 :(得分:2)

我不知道这是否会“最快”,但这里有一种方法可以避免循环内循环:

arr=(Adam Bob Carl Daniel)
read -p "Enter usernames, separated by a space: " -a usernames
already=()
for name in "${usernames[@]}"
do
   [[ " ${arr[*]} " == *" $name "* ]] && already+=($name)
done
[ "${already[*]}" ] && echo "[ ${already[*]} ] already registered"

示例:

$ bash script.sh
Enter usernames, separated by a space: Emma Carl Bob Frank
[ Carl Bob ] already registered

具有连续循环的版本

根据您在评论中的要求,这会不断循环。我还用新名称更新了arr

arr=(Adam Bob Carl Daniel)
while true
do
    read -p "Enter usernames, seperated by a space: " -a usernames
    already=()
    for name in "${usernames[@]}"
    do
       if [[ " ${arr[*]} " == *" $name "* ]]
       then
          already+=($name)
       else
          arr+=($name)
       fi
    done
    [ "${already[*]}" ] && echo "[ ${already[*]} ] already registered"
done