确认Shell脚本输入

时间:2015-03-14 23:18:45

标签: bash shell sh

我正在编写一个脚本来执行重复性任务,该任务只会更改基本值和位置,例如用户名。

我已经编写了提示输入用户名并验证其尚未使用的代码。我现在试图提示用户是否收到的脚本输入是否正确以及是否要更改它。我的问题是,如果输入正确,它会保持循环。有人有什么建议吗?

clear
confirm () {
    # call with a prompt string or use a default
    echo "CMIT # ${1}"
    read -r -p "CMIT [Y/n/q] > " answer
    case "${answer}" in
        [yY]|[yY][eE][sS]) false ;;
        [nN]|[nN][oO]) true ;;
        [qQ]|[qQ][uU][iI][tT]) exit 1 ;;
    esac
}

while true;  do
    OE_USER=
    while (id -u $OE_USER > /dev/null 2>&1); do
        echo "CMIT # What user will this run under?"
        read -r -p "CMIT > " OE_USER
        if id -u $OE_USER > /dev/null 2>&1; then
            echo "CMIT # Bad User Name. Try Again"
        fi
    done
    clear
    confirm "Continue installing using '$OE_USER' as the server name?"
done

2 个答案:

答案 0 :(得分:0)

你可以在一个好的答案中声明一个在confirm函数中设置的全局标志,或者你可以在你的while循环中使用条件中的一个return语句进行测试。

还有其他选项,例如在测试用户输入后使用递归调用。这将消除对while循环的需要,但也需要使初始输入成为一个函数。

答案 1 :(得分:0)

您可以使用功能的退出状态:

更改“yes”情况以执行“true”,并将“no”情况更改为“false”。然后

while true; do
    # ...
    if confirm "Continue installing using '$OE_USER' as the server name?" 
    then
        break
    fi
done