Today, I didn’t proceed to my next lesson that I was going to study. Instead, I practiced what I have learned in the topic Data Types and Operators. I experimented by writing my own Bash scripts to apply variables, arithmetic operations, and user input. For example, I created a calculator script where the user can choose an operation like add, sub, mul, or div and enter two numbers, and the script outputs the result while checking for errors like division by zero. Doing these hands-on experiments helped me understand the concepts more deeply and strengthened my coding skills.
Simple Calculator:
#!/bin/bash
# Ask the user for the operation
read -p "Enter operation (add, sub, mul, div): " operation
# Ask the user for two numbers
read -p "Enter first number: " num1
read -p "Enter second number: " num2
# Perform the operation using case
case $operation in
add)
result=$((num1 + num2))
echo "Result: $result"
;;
sub)
result=$((num1 - num2))
echo "Result: $result"
;;
mul)
result=$((num1 * num2))
echo "Result: $result"
;;
div)
if [ $num2 -eq 0 ]; then
echo "Error: Division by zero is not allowed!"
else
result=$((num1 / num2))
echo "Result: $result"
fi
;;
*)
echo "Invalid operation! Please choose add, sub, mul, or div."
;;
esac
How it works:
read -p prompts the user for input on the same line.
case ... esac checks which operation was entered.
Arithmetic is done using $(( )).
Division checks for zero to avoid errors.
* in case handles invalid input.
Example Run:
Enter operation (add, sub, mul, div): add
Enter first number: 10
Enter second number: 5
Result: 15
Top comments (0)