Can you show a practical example?

QuestionsQuestions8 SkillsProYour First Linux LabDec, 06 2025
070

Certainly! Here’s a practical example of a shell script that uses the clear command to manage terminal clutter and provides a simple menu for the user to choose from. This script will demonstrate how to clear the screen and interact with the user.

#!/bin/bash

# Clear the terminal screen
clear

# Display a welcome message
echo "Welcome to the Simple Menu Script!"
echo "Please choose an option:"
echo "1. Display current date and time"
echo "2. List files in the current directory"
echo "3. Show system information"
echo "4. Exit"

# Read user input
read -p "Enter your choice [1-4]: " choice

# Process user input
case $choice in
    1)
        clear
        echo "Current date and time: $(date)"
        ;;
    2)
        clear
        echo "Files in the current directory:"
        ls -l
        ;;
    3)
        clear
        echo "System Information:"
        uname -a
        ;;
    4)
        clear
        echo "Exiting the script. Goodbye!"
        exit 0
        ;;
    *)
        clear
        echo "Invalid choice. Please run the script again."
        ;;
esac

# Pause before exiting
read -p "Press [Enter] to continue..."

How the Script Works

  1. Clear the Screen: The script starts by clearing the terminal screen using the clear command to provide a clean interface for the user.

  2. Display Menu Options: It presents a simple menu with four options for the user to choose from.

  3. Read User Input: The script uses the read command to capture the user's choice.

  4. Process Input with a Case Statement:

    • Depending on the user's choice, the script performs different actions:
      • Option 1: Displays the current date and time.
      • Option 2: Lists files in the current directory.
      • Option 3: Shows system information.
      • Option 4: Exits the script.
      • Invalid Input: If the user enters an invalid option, it informs them and prompts to run the script again.
  5. Pause Before Exiting: After executing the chosen option, the script pauses and waits for the user to press Enter before exiting.

Running the Script

  1. Create the Script: Save the script in a file named simple_menu.sh.

  2. Make it Executable: Run the following command to make the script executable:

    chmod +x simple_menu.sh
  3. Execute the Script: Run the script using:

    ./simple_menu.sh

Summary

This practical example demonstrates how to use the clear command in a shell script to manage terminal clutter while providing an interactive menu for users. It showcases basic scripting concepts such as user input, conditional statements, and output formatting.

If you have any more questions or need further clarification, feel free to ask!

0 Comments

no data
Be the first to share your comment!