我写了询问类似这样的用户输入的功能:zsh - 用默认值读取用户输入 - 空输入不为空?
function is_confirmed {
read -rs -k 1 ans
if [[ "${ans}" == "n" || "${ans}" == "N" ]]; then
printf "No\n"
return 1
fi
if [[ "${ans}" == "y" || "${ans}" == "Y" ]]; then
printf "Yes\n"
return 0
fi
# here is my actual problem!!! this doesnt work when user input is blank!
if [[ "${ans}" == "" ]]; then
printf "Yes!\n"
return 1
fi
# Output is Damn!
printf "Damn"
return 1
}
的伟大工程,到目前为止,不过,我想设置成“yes”作为默认answear,所以当用户输入什么,只是按下回车,它应该回落到“是”,所以我尝试了|| "$ans" == ""
但仍然回落到“该死”
怎么回事?当我在echo $ans
它是空的函数的结尾......
编辑1:
这是发生了什么:
e_ask "Are you sure you want to install?\nWarning: This may override some files in your home directory."
if is_confirmed; then
echo "Great!"
else
e_error "Aborting..."
fi
这里的功能是:
function e_ask {
printf "\n$1\n"
printf "(Y/n): "
}
function e_warn {
printf "Warning: $1\n"
}
function e_error {
printf "Error: $1\n"
exit 1
}
这并不能解决我的问题。当我没有在shell中输入任何内容,只需按回车,以便$ ans应该是一个空字符串,'$ ans ==“”''仍然会回到“该死”。 –
@MartinBroder对不起,我误解了。如果你输入'N'或'n',你想输出“No”;如果输入'y','Y'或什么都不输入,输出“Yes”在这种情况下,您只需更改默认情况,或者用'y | Y |“”'替换'y | Y'。 – giordano
没问题, 嗯是的,当我输入'Y','Y',“”和“否”时,如果它是'N',''n'或其他任何东西('a', 'b','c' ...) –