Can case statements create simple CLIs?

QuestionsQuestions4 SkillsProDec, 23 2025
0168

Yes, absolutely! In fact, case statements are the most common way to create CLIs (Command Line Interfaces) in Shell scripting.

There are two main types of simple CLIs you can build with case:

1. The "Menu-Driven" CLI

This is an interactive menu where the user selects an option from a list. It usually lives inside a while loop so the program stays open.

Example: lab_tool.sh

#!/bin/bash
while true; do
    echo "--- Lab Management Tool ---"
    echo "a) Create a new file"
    echo "b) System status"
    echo "q) Quit"
    read -p "Selection: " choice

    case $choice in
        a|A) touch "new_file_$(date +%s).txt" ;;
        b|B) free -m ;; # Shows memory usage
        q|Q) break ;;   # Breaks the loop to exit
        *) echo "Invalid option!" ;;
    esac
done

2. The "Command-Argument" CLI

This style is like git or apt, where you pass a command directly when running the script (e.g., ./script.sh start).

Example: service_manager.sh

#!/bin/bash
COMMAND=$1

case "$COMMAND" in
    "start")
        echo "Starting the service..."
        # logic to start service
        ;;
    "stop")
        echo "Stopping the service..."
        # logic to stop service
        ;;
    "status")
        echo "Service is running."
        ;;
    *)
        echo "Usage: $0 {start|stop|status}"
        exit 1
        ;;
esac

Why case is perfect for CLIs:

  1. Input Normalization: Using a|A) or start|START) makes your CLI user-friendly by accepting both upper and lowercase.
  2. Usage Instructions: The *) default case provides an easy way to show the user how to use the script correctly if they type the wrong thing.
  3. Clean Logic: Each "command" has its own block, making it easy to add new features as your CLI grows.

If you combine this with the read command (for input) and while loops (for persistence), you can build very functional tools for your Linux environment!

0 Comments

no data
Be the first to share your comment!