MC, 2025
Ilustracja do artykułu: Create Menu in Bash Script: A Complete Guide with Examples

Create Menu in Bash Script: A Complete Guide with Examples

Have you ever wanted to add a menu to your Bash scripts to make them more interactive and user-friendly? Whether you're working on a small personal project or developing a complex system, a well-designed menu can enhance the user experience. In this article, we’ll explore how to create a menu in a Bash script, providing practical examples along the way!

What is a Bash Script Menu?

A Bash script menu allows users to choose from a list of options that are displayed in the terminal. Instead of typing long commands or providing multiple arguments, the user can simply select an option, and the script will execute the corresponding action. This is particularly useful for creating interactive scripts for system administration, data processing, or any other task where user input is required.

Why Should You Use a Menu in Your Bash Script?

Incorporating a menu into your Bash script can improve the overall flow and usability. Here are a few reasons why you should consider using a menu:

  • Improved User Interaction: Menus provide a clear and straightforward way for users to interact with your script.
  • Less Mistakes: By offering options to choose from, you reduce the chances of user input errors, making your script more reliable.
  • Cleaner and Organized Code: Menus help keep the script organized and readable, especially when the script becomes larger.

Basic Syntax for Creating a Menu in Bash

Let’s start by understanding the basic syntax of a Bash script menu. We’ll break it down into a simple example. Below is a basic Bash script that creates a menu for the user to choose from:

#!/bin/bash

# Function to display the menu
show_menu() {
    echo "Select an option:"
    echo "1. Option 1"
    echo "2. Option 2"
    echo "3. Option 3"
    echo "4. Exit"
}

# Read user choice
read_choice() {
    read -p "Enter your choice: " choice
}

# Main loop
while true; do
    show_menu
    read_choice
    case $choice in
        1) echo "You selected Option 1";;
        2) echo "You selected Option 2";;
        3) echo "You selected Option 3";;
        4) echo "Exiting..."; exit;;
        *) echo "Invalid choice, please try again";;
    esac
done

This script displays a menu with four options. The user can choose one of the options by entering the corresponding number. Let’s walk through the parts of this script:

  • show_menu() function: This function displays the menu options to the user.
  • read_choice() function: This function reads the user’s input from the terminal.
  • while loop: This is where the script continuously displays the menu until the user chooses to exit (Option 4).
  • case statement: This is the part that processes the user’s input and executes the corresponding action based on the choice.

Customizing Your Menu

Now that you understand the basic structure, let’s take a look at some ways to customize your menu to meet your needs.

Adding More Options

You can easily add more options to the menu. For example, if you want to add an option for checking system disk usage, you can do this:

show_menu() {
    echo "Select an option:"
    echo "1. Check Disk Usage"
    echo "2. List Files in Current Directory"
    echo "3. Exit"
}

read_choice() {
    read -p "Enter your choice: " choice
}

while true; do
    show_menu
    read_choice
    case $choice in
        1) df -h;;
        2) ls -l;;
        3) echo "Exiting..."; exit;;
        *) echo "Invalid choice, please try again";;
    esac
done

Now, when the user selects Option 1, the script will display the system’s disk usage in a human-readable format (thanks to the df -h command). Option 2 will list the files in the current directory, and Option 3 will exit the script.

Making the Menu More Interactive

You can enhance the user experience by adding colors to your menu. Bash allows you to use ANSI escape codes to add colors to the terminal. For instance, you could highlight the options or display messages in different colors:

RED='\033[0;31m'
GREEN='\033[0;32m'
NC='\033[0m' # No Color

show_menu() {
    echo -e "${GREEN}Select an option:${NC}"
    echo -e "${RED}1.${NC} Check Disk Usage"
    echo -e "${RED}2.${NC} List Files"
    echo -e "${RED}3.${NC} Exit"
}

read_choice() {
    read -p "Enter your choice: " choice
}

while true; do
    show_menu
    read_choice
    case $choice in
        1) df -h;;
        2) ls -l;;
        3) echo "Exiting..."; exit;;
        *) echo "Invalid choice, please try again";;
    esac
done

In this updated version, the menu options are displayed in red, while the prompt text is green. The NC variable resets the color after each option to prevent the rest of the terminal text from being affected.

Handling User Input: Error Checking

It’s important to handle invalid user input. In the previous examples, the script checks whether the user selects a valid option. If the input doesn’t match any of the available options, the script informs the user and prompts for input again. This is done using the case statement in conjunction with the *) wildcard, which handles invalid input and prompts the user to try again.

Using Functions to Improve Structure

As your script becomes more complex, you may want to break the code into smaller, reusable functions. This improves the readability and maintainability of your script. Here's an example:

show_disk_usage() {
    df -h
}

show_file_list() {
    ls -l
}

exit_script() {
    echo "Exiting..."
    exit
}

show_menu() {
    echo "Select an option:"
    echo "1. Check Disk Usage"
    echo "2. List Files"
    echo "3. Exit"
}

read_choice() {
    read -p "Enter your choice: " choice
}

while true; do
    show_menu
    read_choice
    case $choice in
        1) show_disk_usage;;
        2) show_file_list;;
        3) exit_script;;
        *) echo "Invalid choice, please try again";;
    esac
done

By creating separate functions for tasks like checking disk usage or listing files, we can keep the main script cleaner and easier to manage. Each function is self-contained, and it's easier to add new functionality or modify existing ones.

Conclusion

Creating a menu in a Bash script is an excellent way to improve user interaction, reduce errors, and make your script more user-friendly. With just a few lines of code, you can create a powerful interactive script that handles multiple tasks. Whether you’re a beginner or an experienced user, adding menus to your scripts can make your projects more dynamic and engaging!

Komentarze (0) - Nikt jeszcze nie komentował - bądź pierwszy!

Imię:
Treść: