-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtask2.sh
executable file
·84 lines (74 loc) · 1.88 KB
/
task2.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#!/bin/bash
# Initialize variables
operation=""
numbers=()
debug_flag=false
# Parse input arguments
while [[ $# -gt 0 ]]; do
case "$1" in
-o)
operation="$2"
shift 2
;;
-n)
shift
while [[ "$1" =~ ^-?[0-9]+$ ]]; do # Allow both positive and negative integers
numbers+=("$1")
shift
done
;;
-d)
debug_flag=true
shift
;;
*)
echo "Invalid option or argument: $1"
exit 1
;;
esac
done
# Check if operation and numbers are provided
if [ -z "$operation" ]; then
echo "Please provide an operation (-o)."
exit 1
fi
if [ ${#numbers[@]} -eq 0 ]; then
echo "Please provide a sequence of numbers (-n)."
exit 1
fi
# Validate if the operation is supported
if [[ "$operation" != "+" && "$operation" != "-" && "$operation" != "*" && "$operation" != "%" ]]; then
echo "Invalid operation: $operation. Please use one of +, -, *, %."
exit 1
fi
# Perform the operation with error handling
result="${numbers[0]}"
for (( i=1; i<${#numbers[@]}; i++ )); do
# Handle division/modulo by zero
if [[ "$operation" == "%" && "${numbers[i]}" -eq 0 ]]; then
echo "Error: Division by zero is not allowed with the '%' operation."
exit 1
fi
case "$operation" in
"+")
result=$((result + numbers[i]))
;;
"-")
result=$((result - numbers[i]))
;;
"*")
result=$((result * numbers[i]))
;;
"%")
result=$((result % numbers[i]))
;;
esac
done
# Debug output if -d flag is set
if [ "$debug_flag" = true ]; then
echo "User: $(whoami)"
echo "Script: $0"
echo "Operation: $operation"
echo "Numbers: ${numbers[*]}"
fi
echo "Result: $result"