1

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

3 Answers 3

9

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
Sign up to request clarification or add additional context in comments.

3 Comments

do I need to have that \c? And do I need to define the choices somewhere?
The '\c' is older syntax for suppressing the newline from echo, you can just use the -n flag if your system supports it. The choices for case can be literals, regexes or variables ( which will get interpolated ).
is there a way to show the choices that are there to the user?
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

Comments

1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.