我的bash脚本进入无限循环

时间:2016-01-25 14:45:56

标签: bash loops

我想从文件中读取存储库名称,显示YES-NO-CANCEL对话框,然后在用户回答“是”时添加存储库。到目前为止,我已经编写了这段代码:

g_dlg_yes=1
g_dlg_no=0
g_dlg_cancel=127

show_confirm_dlg()
{
    local prompt="$* [y(es)/n(o)/c(ancel)]: "
    local resp=""
    while [ "$resp" != "y" ] && [ "$resp" != "n" ] && [ "$resp" != "c" ]; do
        echo "$prompt"
        read resp
    done
    if [ "$resp" = "y" ]; then
        g_dlg_res=$g_dlg_yes
    elif [ "$resp" = "n" ]; then
        g_dlg_res=$g_dlg_no
    elif [ "$resp" = "c" ]; then
        g_dlg_res=$g_dlg_cancel
    else
        g_dlg_res=$g_dlg_cancel
    fi
}

add_repo()
{
    local filename="/home/stojan/repo.list"
    while read -r line
    do
        local repo_name=$line
        echo "Name read from file - $line"
        show_confirm_dlg "Add repository $repo_name?"
        local rc=$g_dlg_res
        if [ $rc -eq $g_dlg_yes ]; then
            add-apt-repository -y $repo_name
            ##echo $repo_name
        elif [ $rc -eq $g_dlg_no ]; then
            echo "Repository $repo_name rejected"
        elif [ $rc -eq $g_dlg_cancel ]; then
            echo "Script cancelled"
            exit 1
        else
            echo "Unknown response. Now cancelling..."
            exit 1
        fi
        echo "Press ENTER..."
        read _

    done < "$filename"
}

add_repo

问题在于,当我运行此脚本时,我陷入show_confirm_dlg()并进入无限循环。这就是脚本不会等待我的输入并反复重复确认。

2 个答案:

答案 0 :(得分:4)

使用read读取标准输入。在重定向中使用read时,它不会从键盘读取,而是从当时的标准输入读取。

C.f:

{
    read a
    echo $a
} < <(echo Hello)

您可以在其他地方复制标准输入,以便能够同时处理多个流:

exec 3<&0          # fd3 now points to the initial stdin
{
    read a         # This reads the "Hello".
    read b <&3     # This reads from the keyboard.
    echo "$a, $b"

} < <(echo Hello)
exec 3<&-          # Close the fd3.

答案 1 :(得分:0)

要从while...do循环获取用户输入,您还可以执行以下操作:

while [ "$resp" != "y" ] && [ "$resp" != "n" ] && [ "$resp" != "c" ]; do
    echo "$prompt"
    read resp </dev/tty
done

请参阅此主题: Read input in bash inside a while loop