Fate Averie
Fate Averie

Reputation: 359

interactive Shell Script

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

Upvotes: 1

Views: 17489

Answers (3)

vlp
vlp

Reputation: 603

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

Upvotes: 1

Dick Faps
Dick Faps

Reputation: 133

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

Upvotes: 1

zellio
zellio

Reputation: 32484

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

Upvotes: 9

Related Questions