-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnumberCountWithFunctions.sh
78 lines (66 loc) · 1.3 KB
/
numberCountWithFunctions.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
#/bin/bash
# This script prints a range of numbers
usage () {
cat <<END
count [-r] [-b n] [-s n] stop
Print each number up to stop, beginning at 0
-b: number to begin with (default: 0)
-h: show this help message
-r: reverses the count
-s: sets step size (default: 1)
END
}
# function to handle errors.
# First argument: error message to print
# Second argument: exit code to exit script with
error () {
echo "Error: $1"
usage
exit $2
} >&2
# Function returns 0 when it's argument is a number
isnum () {
[[ $1 =~ ^[0-9]+$ ]]
}
declare reverse=""
declare -i begin=0
declare -i step=1
while getopts ":hb:s:r" opt; do
case $opt in
r)
reverse="yes"
;;
b)
isnum ${OPTARG} || error "${OPTARG} is not a number" 1
start="${OPTARG}"
;;
h)
usage
exit 0
;;
s)
isnum ${OPTARG} =~ ^[0-9]+$ || error "${OPTARG} is not a number" 1
step="${OPTARG}"
;;
:)
error "Option -${OPTARG} is missing an argument" 2
;;
\?)
error "Unknown option: -${OPTARG}" 3
;;
esac
done
shift $(( OPTIND -1 ))
[[ $1 ]] || error "missing an argument" 2
isnum $1 || error "$1 is not a number" 1
declare end="$1"
if [[ ! $reverse ]]; then
for (( i=start; i <= end; i+=step )); do
echo $i
done
else
for (( i=end; i >= start; i-=step )); do
echo $i
done
fi
exit 0