交互式Shell脚本(interactive Shell Script)

2019-09-26 05:03发布

如何创建一个简单的shell脚本,请求来自用户的简单输入,然后只运行与预定义的选择相关的命令,例如

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

Answer 1:

您可以通过从用户接受输入read ,你可以使用一个case ... esac块做不同的事情。

阅读作为其参数,在其中将其存储的值的变量名

read foo

将在来自用户的vaue并将其存储在$foo

要提示用户输入您需要使用的回声。

echo "What is your favourite color?"
read color

最后,大多数shell脚本支持的情况下操作。 其采取的形式

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


Answer 2:

#!/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


Answer 3:

您好是简单的例子,该怎么办呢

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

对于源,请点击此处源



文章来源: interactive Shell Script