Handling user input of * with case in shell script

Question about handling user input with `case` in a shell script. Using the `case` statement is an efficient way to handle different user inputs in a shell script, especially when you have multiple options to manage. Here's how you can use `case` to handle user input in a shell script:


```bash

#!/bin/bash


# Display a menu to the user

echo "Select an option:"

echo "1. Option 1"

echo "2. Option 2"

echo "3. Option 3"

echo "Q. Quit"


# Read user input

read choice


# Use case to handle the user's choice

case "$choice" in

  1)

    echo "You selected Option 1"

    # Perform actions for Option 1

    ;;

  2)

    echo "You selected Option 2"

    # Perform actions for Option 2

    ;;

  3)

    echo "You selected Option 3"

    # Perform actions for Option 3

    ;;

  [qQ])

    echo "Goodbye!"

    # Optionally, you can include actions to quit the script here

    ;;

  *)

    echo "Invalid choice. Please select a valid option."

    ;;

esac

```


In this example:


1. A menu is displayed to the user.


2. The `read` command reads the user's input and stores it in the `choice` variable.


3. The `case` statement is used to compare the user's input (`$choice`) with various patterns. Each pattern corresponds to a menu option.


4. For each option, you can include the desired actions or commands to execute when the user selects that option.


5. The `*)` pattern at the end of the `case` statement acts as a catch-all for any input that doesn't match the previous patterns. In this case, it prints an "Invalid choice" message.


6. You can include a pattern for quitting the script (e.g., `[qQ]`) and provide actions to exit the script gracefully.


By using `case`, you can efficiently handle different user inputs and execute the corresponding actions or commands based on the user's selection.

Comments

Popular posts from this blog

bad character U+002D '-' in my helm template

GitLab pipeline stopped working with invalid yaml error

How do I add a printer in OpenSUSE which is being shared by a CUPS print server?