Bash输入变量&环

时间:2014-05-13 23:10:42

标签: bash loops

我的剧本

#!/bin/bash
while :
do
    echo "[*] 1 - Create a gnome-terminal"
    echo "[*] 2 - Display Ifconfig"
    echo -n "Pick an Option > "
    read Input

    if [ "$Input" = "1" ]; then
        gnome-terminal
        sleep 3
    echo "[*] 1 - Create a gnome-terminal"
    echo "[*] 2 - Display Ifconfig"
    echo -n "Pick an Option > "
    read Input

    fi

    if [ "$Input" = "2" ]; then
        clear
        ifconfig
    echo "[*] 1 - Create a gnome-terminal"
    echo "[*] 2 - Display Ifconfig"
    echo -n "Pick an Option > "
    read Input

    fi

done

不重用Input变量,例如,如果要连续多次运行ifconfig选项。它重新检查第一个变量字符串以查看它是否匹配“1”,当它不匹配时它回显选项列表。关于如何使任何输入变量可以访问的任何想法,无论何时使用它?

2 个答案:

答案 0 :(得分:4)

问题是你在每次迭代时都要写出两次菜单。停止这样做:

#!/bin/bash
while :
do
    echo "[*] 1 - Create a gnome-terminal"
    echo "[*] 2 - Display Ifconfig"
    echo -n "Pick an Option > "
    read Input

    if [ "$Input" = "1" ]; then
        gnome-terminal
        sleep 3
    fi

    if [ "$Input" = "2" ]; then
        clear
        ifconfig
    fi
done

答案 1 :(得分:2)

使用select而不是滚动自己的菜单:

choices=(
    "Create a gnome-terminal" 
    "Display Ifconfig"
)
PS3="Pick an Option > "
select action in "${choices[@]}"; do 
    case $action in 
        "${choices[0]}") gnome-terminal; sleep 3;; 
        "${choices[1]}") clear; ifconfig;; 
        *) echo invalid selection ;; 
    esac
done

select默认为您提供无限循环。如果您想要突破它,请将​​break语句放入case分支。