gpt4 book ai didi

macos - zsh - 使用默认值读取用户输入 - 空输入不为空?

转载 作者:行者123 更新时间:2023-12-04 16:16:11 24 4
gpt4 key购买 nike

我写了一个像这样要求用户输入的函数:

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
}

到目前为止效果很好,但是,我想将"is"设置为默认回答,所以当用户什么都不输入并按下回车键时,它应该回退到"is",所以我尝试了 || "$ans"== "" 但仍然会回到 "Damn"

怎么会呢?当我在函数末尾 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
}

最佳答案

A case当您想考虑许多不同的值和一个默认值时会更好

function is_confirmed {    read -rs -k 1 ans    case "${ans}" in    y|Y|$'\n')        printf "Yes\n"            return 0        ;;    *)  # This is the default        printf "No\n"            return 1    esac}

关于macos - zsh - 使用默认值读取用户输入 - 空输入不为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17047913/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com