如何使用Zsh的read -q缺省设置为“ Y”

时间:2018-07-23 20:49:27

标签: input zsh

由于某种原因,即使我希望它得到一个空字符串或换行符,当我按下 return 时,此函数总是获得“ 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 个答案:

答案 0 :(得分:1)

这是使用选项-q时的预期行为。这是ZSH manual的相关部分:

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

[...]

     

-q

     

仅从终端读取一个字符,如果此字符是'y'或'y',则将 name 设置为'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]"