我写了一个要求用户输入的函数,如下所示:
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
}
到目前为止效果很好,但是,我想将“是”设置为默认答案,所以当用户什么都不输入并按回车键时,它应该回退到“是”,所以我尝试过,|| "$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
}