-
Notifications
You must be signed in to change notification settings - Fork 1
/
querystring.sh
65 lines (57 loc) · 1.37 KB
/
querystring.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
querystring() {
local path
path="$(echo "$1" | cut -d"?" -f1)"
echo "${1:$(( ${#path} + 1 ))}"
}
querystring_escape() {
local input=
if [ $# -gt 0 ]; then
input="$*"
else
# assume stdin
input="$(cat)"
fi
printf "%s" "$input" | while IFS='' read -n 1 -r c; do
if [ "$c" = "!" ] || [ "$c" = "(" ] || [ "$c" = ")" ] || [ "$c" = "'" ] || [ "$c" = "*" ]; then
printf "$c"
else
case $c in
[a-zA-Z0-9.~_-]) printf "$c" ;;
*) printf '%%%02X' "'$c"
esac
fi
done
}
# Credit: https://stackoverflow.com/a/37840948/376773
querystring_unescape() {
local input=
if [ $# -gt 0 ]; then
input="$*"
else
# assume stdin
input="$(cat)"
fi
input="${input//+/ }"
printf '%b' "${input//%/\\x}"
}
querystring_parse() {
local name
local next
local value
local input="$1"
shift
local i=1
next="$(echo "$input" | awk -F'&' '{print $1}')"
while [ -n "$next" ]; do
name="$(echo "$next" | awk -F= '{print $1}' | querystring_unescape)"
for wanted in $*; do
if [ "$wanted" = "$name" ]; then
value="$(echo "$next" | awk '{print substr($0, '"$(( ${#name} + 2 ))"')}' | querystring_unescape)"
eval "$name=$(echo "$value" | sed -e "s/'/'\\\\''/g; 1s/^/'/; \$s/\$/'/")"
break
fi
done
i="$(( i + 1 ))"
next="$(echo "$input" | awk -F'&' '{print $'"$i"'}')"
done
}