【问题标题】:Multiple words as a possible variable in bash多个单词作为bash中的可能变量
【发布时间】:2014-10-03 17:06:42
【问题描述】:

Hi=("Hi" "Hello" "Hey") 行有可能的输入。我尝试在单词之间添加逗号,但这也不起作用。如果输入了 hihellohey,我需要它来回显“Hi”。现在只有 Hi 有效。我想我正在寻找的是一种为一个词制作“同义词”的方法。用一个词代替另一个词的能力。

    clear; echo
    shopt -s nocasematch
    echo; read -p "    > " TextInput

    Hi=("Hi" "Hello" "Hey")

     if [[ "$TextInput" == $Hi ]]; then
    clear; echo; echo
    echo -e "    >> Hi"
    echo

     else
    clear; echo; echo
    echo -e "    >> Error"
    echo
    fi

我知道我可以使用

     if [[ "$TextInput" == "Hi" ]] || [[ "$TextInput" == "Hello" ]] || [[ "$TextInput" == "Hey" ]]; then

但这会变得太长了。

【问题讨论】:

  • bash 数组不适用于这种集合操作,因为它们是作为一种二级引用类型而不是作为容器类型开发的。

标签: linux bash if-statement multiple-conditions


【解决方案1】:

如果您的目标是 bash 4.0 或更高版本,则关联数组将起作用:

TextInput=Hello
declare -A values=( [Hi]=1 [Hello]=1 [Hey]=1 )

if [[ ${values[$TextInput]} ]]; then
  echo "Hi there!"
else
  echo "No Hi!"
fi

这是一个 O(1) 查找,比基于 O(n) 循环的遍历更快。


也就是说,如果您要匹配的项目列表是硬编码的,只需使用 case 语句:

case $TextInput in
  Hi|Hello|Hey) echo "Hi there!" ;;
  *)            echo "No Hi!     ;;
esac

这还具有与任何符合 POSIX sh 的 shell 兼容的优点。

【讨论】:

  • 谢谢!如果我添加了 elif 有没有办法使用相同的“Hi”选项? elif [[ "$TextInput" == "Hi, how are you" ]]; thenecho "Good"
  • @Seaner992,我不确定你的问题是什么意思。 [[ ]] 的行为方式相同,无论它是否在 if 语句的 then 部分、elif 中,或者根本不在 if 中。在您的原始问题中,我没有看到任何地方有通往“好”的路径。
  • 请不要使用 pastebin.com —— 它充满了不运行 Adblock 的任何人的广告。 gist.github.com 更友好。
  • gist.github.com/anonymous/aee1c2d3302f270829db 我希望将您的答案用于其他 if 语句,这样就不必输入一堆 Hi/Hey/Hello。
  • ...所以,declare -A responses=( ["Hi how are you"]=1 ["Hey how are you"]=1 )[[ ${responses[$TextInput]} ]] 进行检查。
【解决方案2】:

看看这个变种:

TextInput="Hello"
Hi=("Hi" "Hello" "Hey")

flag=0

for myhi in ${Hi[@]}; do
    if [[ "$TextInput" == "$myhi" ]]; then
        flag=1
        break
    fi
done

if [[ $flag == 1 ]]; then
    echo "Hi there!"
else
    echo "No Hi!"
fi

问题是:使用标志 + for 循环。如果设置了标志 (=1),则 TextInput 等于您的 Hi 数组中的某个值。

【讨论】:

    【解决方案3】:

    根据你的需要,你也可以使用开关:

    case "$input" in
      "Hi"|"He"*)
        echo Hello
        ;;
      *)
        echo Error
        ;;
      esac
    

    这还允许您指定模式。

    【讨论】:

      【解决方案4】:

      使用 bash 的模式匹配:

      $ Hi=(Hi Hello Hey)
      $ input=foo
      $ if (IFS=:; [[ ":${Hi[*]}:" == *:"$input":* ]]); then echo Y; else echo N; fi
      N
      $ input=Hey
      $ if (IFS=:; [[ ":${Hi[*]}:" == *:"$input":* ]]); then echo Y; else echo N; fi
      Y
      

      我在这里使用括号来生成一个子shell,因此对 IFS 变量的更改不会影响当前的 shell。

      【讨论】:

        猜你喜欢
        • 2016-04-18
        • 2021-03-04
        • 2012-06-12
        • 2017-10-25
        • 2014-01-25
        • 1970-01-01
        • 1970-01-01
        • 2019-06-12
        • 1970-01-01
        相关资源
        最近更新 更多