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

如何使用zsh的read-q默认为“y”

  •  0
  • iconoclast  · 技术社区  · 7 年前

    出于某种原因,当我点击时,这个函数总是得到“n”作为输入 返回 ,即使我希望它得到一个空字符串或换行符。除了“n”,我希望它能得到任何东西。

    function readtest() {-
      local YorN  # this ensures there is no left-over value in YorN
      #echo -ne "Go ahead?  [Y/n]"; read -q YorN  # this version the same result as the next line
      read -q "YorN?Go ahead?  [Y/n]"
      [[ "$YorN" = "\n" ]] && echo "Matched Newline" # I don't really expect this to return true: it's just here to test
      [[ "$YorN" != "n" ]] && echo "Do the thing!" # I expect this test to return true... this is the weird thing, and central to my question
      echo "## $YorN ##"  # I always get "## n ##"
    }
    

    为什么 YorN “N”????

    1 回复  |  直到 7 年前
        1
  •  1
  •   Adaephon Radek    7 年前

    这是使用选项时的预期行为 -q . 以下是 ZSH manual :

    read [ -rszpqAclneE ] [ -t [ num ] ] [ -k [ num ] ] [ -d delim ]
         [ -u n ] [ name[?prompt] ] [ name ... ]
    

    […]

    - q

    只从终端读取一个字符并设置 名称 y 如果这个角色是 Y Y 并且 n 否则。设置此标志时,仅当字符为 Y Y . 此选项可与超时一起使用(请参见 -t );如果读取超时或遇到文件结尾,则返回状态2。输入从终端读取,除非 -u -p 存在。此选项也可以在zle小部件中使用。

    如果你想有相反的行为,即只有当你输入n或n时才假设一个否定的答案,否则只假设一个肯定的答案,你可以使用这个选项。 -k 1 :

    function readtest {
        local YorN
        read -q "YorN?Go ahead? [Y/n]"
        if [[ ${(U)YorN} == "N" ]] ; then 
            echo "Don't do the thing!"
        else
            echo "Go ahead!" 
        fi
    }
    

    另一种选择是颠倒问题:

    read -q "YorN? Stop here? [y/N]"