【问题标题】:Prompt if answer is correct then validate in Bash提示答案是否正确,然后在 Bash 中验证
【发布时间】:2014-08-13 17:26:10
【问题描述】:

这是在安装开始时执行的初始脚本。它将捕获用户输入,然后将其写入另一个调用变量的 bash 脚本。它的效果很好,但是,我想为每个问题添加一个确认。

例如,在用户输入电子邮件后,我希望它回显他们输入的内容,以确认它是否正确。如果是,则将其写入另一个脚本并继续下一个问题。如果不循环回到语句的开头,以便他们可以更正答案。完成后,我想回应一下结果。

如果有人可以提供一些指针,那就太好了。我在看这些例子In Bash, how to add "Are you sure [Y/n]" to any command or alias?

#!/bin/bash
read -p "Who is the primary Email recipient? : " TO
    echo "TO=$TO" >> /var/tmp/ProcMon
read -p "What is the server hostname : " FROM
    echo "FROM=$FROM" >> /var/tmp/ProcMon

【问题讨论】:

  • 我确实看到了这个,但它只是一个是或否语句,如果用户选择否,它只会取消我不需要的没有循环返回。

标签: bash unix


【解决方案1】:
function prompt_and_confirm {
    local var=$1
    local prompt=$2
    local value
    local -u ans

    while :; do
        read -p "$prompt" value
        read -p "You entered: '$value': confirm [y/n] " ans
        [[ ${ans:0:1} == "Y" ]] && break
    done
    echo "$var=$value"
}

prompt_and_confirm TO   "Who is the primary Email recipient? : " >> /var/tmp/ProcMon
prompt_and_confirm FROM "What is the server hostname? : "        >> /var/tmp/ProcMon

注意事项:

【讨论】:

  • 非常感谢你,它很干净,而且是我所需要的。
  • 不要把它拖出来,但你愿意提供这个代码的简要说明以便我学习吗?
  • +1。注意local -u / declare -u 需要 bash 4+;早期版本只能使用local[[ $ans =~ ^[yY] ]] 作为条件。
猜你喜欢
  • 2020-01-16
  • 1970-01-01
  • 1970-01-01
  • 2021-12-30
  • 2011-02-09
  • 2018-11-30
  • 1970-01-01
  • 1970-01-01
  • 2022-11-13
相关资源
最近更新 更多