Unix环境下几何图形计算器Shell脚本菜单循环问题求助
Hey there! Let's get your geometry calculator's menu loop working properly. I spotted a few syntax issues and missing loop logic in your partial script—here's how to fix it and get a fully functional version up and running.
First, let's go over the issues in your current code:
- When reading the username, you used
read $username—it should beread username(the$isn't needed here) - Your script cuts off mid-
echo(theec...is a typo forecho) - Most importantly, there's no loop structure to bring the user back to the main menu after they finish a calculation
Here's a complete, working version of your script with a functional menu loop:
#!/bin/bash # Welcome message and username handling echo "Welcome, please enter username:" read username # Get full name from system (fallback to username if not available) full_name=$(getent passwd "$USER" | cut -d: -f5 | cut -d, -f1) echo "WELCOME $full_name, This is a basic calculator for squares, circles, and rectangles." # Infinite loop to keep the menu running while true; do echo -e "\nPlease choose an option to continue:" echo "1. Rectangle (Area & Perimeter)" echo "2. Circle (Area & Circumference)" echo "3. Square (Area & Perimeter)" echo "4. Exit" read choice # Handle user selection with case statement case $choice in 1) echo "Enter rectangle length:" read length echo "Enter rectangle width:" read width area=$(echo "$length * $width" | bc) perimeter=$(echo "2 * ($length + $width)" | bc) echo "Rectangle Area: $area" echo "Rectangle Perimeter: $perimeter" ;; 2) echo "Enter circle radius:" read radius # Use bc with math library for pi (scale sets decimal precision) area=$(echo "scale=2; 3.14159 * $radius * $radius" | bc) circumference=$(echo "scale=2; 2 * 3.14159 * $radius" | bc) echo "Circle Area: $area" echo "Circle Circumference: $circumference" ;; 3) echo "Enter square side length:" read side area=$(echo "$side * $side" | bc) perimeter=$(echo "4 * $side" | bc) echo "Square Area: $area" echo "Square Perimeter: $perimeter" ;; 4) echo "Goodbye $username!" exit 0 ;; *) echo "Invalid option! Please choose 1, 2, 3, or 4." ;; esac done
Key improvements explained:
- Infinite loop:
while truekeeps the menu running until the user selects option 4 to exit - Proper input handling: Fixed the
readsyntax for username and menu choices - Case statement: Cleanly handles each menu option, with calculations using
bcfor basic arithmetic (supports decimals!) - Error handling: Catches invalid inputs and prompts the user to try again
- Completed functionality: Added actual calculations for each geometric shape
To use this script:
- Save it as
geometry_calculator.sh - Make it executable with
chmod +x geometry_calculator.sh - Run it with
./geometry_calculator.sh
内容的提问来源于stack exchange,提问作者T Von B
相关产品推荐
相关产品推荐

