interactive Shell Script

Fate Averie picture Fate Averie · May 6, 2013 · Viewed 16k times · Source

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

Answer

zellio picture zellio · May 6, 2013

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