简体   繁体   English

确认Shell脚本输入

[英]Confirming Shell Script Input

I'm writing a script to preform a repetitive task that only changes basic values and locations such as user name. 我正在编写脚本以执行重复性任务,该任务仅更改基本值和位置(例如用户名)。

I've written up code that prompts for a username and verifies that it is not already in use. 我已经编写了提示用户名并验证用户名尚未使用的代码。 I'm now trying to prompt the user if the input the script received is correct and if it is not to change it. 我现在尝试提示用户,如果收到的脚本输入正确并且不更改它。 My issue is that if the input is correct it keeps looping. 我的问题是,如果输入正确,它将不断循环。 Anyone have any suggestions? 有人有什么建议吗?

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

Wow. 哇。 Stupid Question. 愚蠢的问题。 Sorry. 抱歉。

clear
GO=true
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]) GO=false ;;
        [nN]|[nN][oO]) GO=true ;;
        [qQ]|[qQ][uU][iI][tT]) exit 1 ;;
    esac
}

while $GO;  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
GO=true

You can either declare a global flag that gets set inside the confirm function on a good answer, or you can use a return statement inside confirm that gets tested in a conditional in your while loop. 您可以声明一个在全局确认函数中设置好的全局标志,以得到一个很好的答案,也可以在confirm内部使用return语句,该语句在while循环中的条件条件下进行测试。

There are other options too, like using a recursive call after testing the user input. 还有其他选项,例如在测试用户输入后使用递归调用。 This would negate the need for the while loop, but create the need to make your initial input a function as well. 这将消除对while循环的需求,但是会产生使初始输入也成为函数的需求。

You can use the exit status of your function: 您可以使用函数的退出状态:

Change the "yes" case to execute "true", and the "no" case to execute "false". 更改“是”情况以执行“ true”,更改“否”情况以执行“ false”。 Then 然后

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM