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.
Example Script: Simple Menu
#!/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
-
Clear the Screen: The script starts by clearing the terminal screen using the
clearcommand to provide a clean interface for the user. -
Display Menu Options: It presents a simple menu with four options for the user to choose from.
-
Read User Input: The script uses the
readcommand to capture the user's choice. -
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.
- Depending on the user's choice, the script performs different actions:
-
Pause Before Exiting: After executing the chosen option, the script pauses and waits for the user to press Enter before exiting.
Running the Script
-
Create the Script: Save the script in a file named
simple_menu.sh. -
Make it Executable: Run the following command to make the script executable:
chmod +x simple_menu.sh -
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!
