代码之家  ›  专栏  ›  技术社区  ›  Seaner992

bash中可以使用多个单词作为变量

  •  -1
  • Seaner992  · 技术社区  · 10 年前

    线路 嗨=(“嗨”“你好”“嗨”) 具有可能的输入。我试过在单词之间加逗号,但也不起作用。如果 你好 , 你好 我需要它回复“嗨”。仅限现在 你好 作品我想我要找的是一个单词的同义词。用一个词替换另一个词的能力。

        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
    

    但这将变得太长了。

    4 回复  |  直到 10 年前
        1
  •  2
  •   Charles Duffy    10 年前

    如果您的目标是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兼容的优点。

        2
  •  1
  •   thiagowfx    10 年前

    看看这个变体:

    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
    

    问题是:使用flag+a for循环。如果标志已设置(=1),则 TextInput 等于你的 Hi 大堆

        3
  •  0
  •   eckes    10 年前

    根据您的需要,您还可以使用开关:

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

    这也允许您指定模式。

        4
  •  0
  •   glenn jackman    10 年前

    使用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。