interactive Shell Script

我们两清 提交于 2020-01-06 01:54:15

问题


how do I create a simple Shell script that asks for a simple input from a user and then runs only the command associated with the predefined choice, for example

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

回答1:


You can take input from a user via read and you can use a case ... esac block to do different things.

Read takes as its argument, the name of the variable into which it will store it's value

read foo

Will take in a vaue from the user and store it in $foo.

To prompt the user for input you will need to use echo.

echo "What is your favourite color?"
read color

Finally, most shell scripts support the case operator. Which take the form

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

Putting it all together:

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



回答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



回答3:


Hi there is simple example how to do it

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

for source click here source



来源:https://stackoverflow.com/questions/16390593/interactive-shell-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!