Case Script

In Linux, a case script is a shell script construct that allows you to evaluate a variable or expression and perform different actions based on its value. It is typically used to provide menu-driven interfaces for command-line tools or to handle user input in scripts.

For example, suppose you have a script that performs different actions based on user input. You can use a case statement to determine which action to perform based on the user’s choice.

Create a file

touch case

Very important, you need to give execute permission to the file, in order to edit it

chmod u+x case

Now you can open the file, by using an editor

vi case

Add the following script

!/bin/bash

echo
echo " Please chose one of the options below "
echo
echo "1. Option 1"
echo "2. Option 2"
echo "3. Option 3"
echo "4. Option 4"
echo
read choices
case $choices in
1) 
echo "You chose Option 1"
;;
2) 
echo "You chose Option 2"
;;
3) 
echo "You chose Option 3"
;;
4) 
echo "You chose Option 4"
;;
*) 
echo "Invalid choice - Bye."

esac

This is a Bash script that presents the user with a menu of four options to choose from. Once the user selects an option, the script uses a case statement to execute a specific action based on the user’s choice.

First, the script displays the menu options. The user is prompted to choose one of the options by entering a number. The user’s input is stored in a variable called choices.

Next, the script uses a case statement to perform a different action based on the value of choices. If the user selects Option 1, the script will print “You chose Option 1”. If the user selects Option 2, the script will print “You chose Option 2”, and so on. If the user enters an invalid choice, the script will print “Invalid choice – Bye.” and exit.

Overall, this script is a simple example of how to create a menu-driven interface for a command-line tool or script in Bash.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top