交互式Shell脚本

时间:2013-05-06 00:41:04

标签: linux shell user-input user-interaction

如何创建一个简单的Shell脚本,该脚本要求用户输入一个简单的输入,然后只运行与预定义选项关联的命令,例如

IF "ON"
Backup Server
ELSEIF "OFF"
Delete Backups
ELSEIF "GREY"
Send Backups
ENDIF

3 个答案:

答案 0 :(得分:7)

您可以通过read从用户那里获取输入,然后您可以使用case ... esac块来执行不同的操作。

Read以其为参数,即变量的名称,它将存储它的值

read foo

将接收用户的vaue并将其存储在$foo

要提示用户输入,您需要使用echo。

echo "What is your favourite color?"
read color

最后,大多数shell脚本都支持case运算符。采取表格

case "value" in
    "CHOICE)
        # Do stuff
        ;;
esac

全部放在一起:

echo "Which choice would you like? \c"
read choice

case "$choice" in

    ON)
        # Do Stuff
        ;;
    OFF)
        # Do different stuff
        ;;
    *)
        echo "$choice is not a valid choice"
        ;;
esac

答案 1 :(得分:1)

#!/bin/bash

select choice in "ON" "OFF" "*"; do
case "$choice" in
    ON) echo "$choice"; # do something; 
    break;;
    OFF) echo "$choice"; # do something; 
    break;;
    *) echo "$choice other"; # do something; 
    break;;
esac
done

答案 2 :(得分:1)

嗨,有一个简单的例子如何做到

while true; do
    read -p 'do you want to continue "y" or "n": ' yn

    case $yn in

        [Yy]* ) echo 'this program continue '; break;;

        [Nn]* ) exit;;

        * ) echo 'Please answer yes or no: ';;

    esac

done

while true; do
    read -p 'press "c" to quit this program: ' c

    case $c in

        [Cc]* ) exit;;

        * ) echo 'for quit this program press "c": ' ;;

    esac

done

来源点击此处source