-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlibrary.sh
122 lines (116 loc) · 3.17 KB
/
library.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
#!/bin/bash
#
# Checks if a flag is present in the arguments.
function hasflag() {
filter=$1
for var in "${@:2}"; do
if [ "$var" = "$filter" ]; then
echo 'true'
break;
fi
done
}
#
# Read the value of an option.
function readopt() {
filter=$1
next=false
for var in "${@:2}"; do
if $next; then
echo $var
break;
fi
if [ "$var" = "$filter" ]; then
next=true
fi
done
}
#
# Returns the first argument if not empty, the second otherwise
function or() {
if [ -n "$1" ]; then
echo $1
else
echo $2
fi
}
#
# Return the nth first arguments
function nfirstargs() {
num=$1
current=0
shift
for var in "$@";do
if [ $current -lt $num ]; then
current=$(($current + 1))
echo $var
else
break
fi
done
}
#
# Filter the specified number of options.
# Examples:
# filteropts 2 -repo -user foo bar baz
# -> foo bar baz
#
# filteropts 2 -repo -user -repo=shellib foo bar baz
# -> foo bar baz
#
# filteropts 2 -repo -user -user=iocanel foo bar baz
# -> foo bar baz
function filteropts() {
num=$1
if echo $num | grep '[^0-9]' > /dev/null; then
echo "$@"
else
skip=$(($num+2))
tofilter=`nfirstargs $@`
next=false
#Loop through arguments starting from skip
for candidate in "${@:$skip}"; do
#If the previous item is the option, then this is the value. So let's skip it.
if $next; then
next=false
continue;
fi
#Loop through items that need to be skiped and see if candidate is included
for i in $tofilter; do
if [ $candidate = "$i" ]; then
next=true
break;
fi
done
if ! $next; then
echo $candidate
fi
done
fi
}
#
# Filter the specified number of flags.
# Example:
# filterflags 2 -version -dry-run foo bar baz
# -> foo bar baz
function filteropts() {
num=$1
if echo $num | grep '[^0-9]' > /dev/null; then
echo "$@"
else
skip=$(($num+2))
tofilter=`nfirstargs $@`
#Loop through arguments starting from skip
for candidate in "${@:$skip}"; do
#Loop through items that need to be skiped and see if candidate is included
for i in $tofilter; do
if [ $candidate = "$i" ]; then
next=true
break;
else
echo $candidate
fi
done
done
fi
}