edit Further review on url_decode()
and the actual 'program'...
The other weird things about url_decode()
are that you are repeating your decoding across two different loops, and carefully interpreting and handling for $num
when $2 = auto
(which isn't 'documented'). Also, since you mentioned that you prefer a more bash
-like solution, perhaps you can consider the following too so that you can even not depend on grep
and sed
:
url_decode() {
local s="$1"; local n=${2:-0};
while [[ $((n--)) -gt 0 || (-z $2 && $s =~ %[[:xdigit:]]{2}) ]]; do
s=$(echo -e ${s//%/\\\x});
done; echo $s
}
Rather than defaulting to 2
, you might as well incrementally apply the decoding until you don't see %XX
, where X
is a hexadecimal character. This is (better) represented using the regex character class [[:xdigit:]]
. =~
replaces the egrep
and ${s//%/\\\x}
replaces the sed
. The loop condition simply says:
- countdown
$n
until it reaches0
, i.e.[$n - 1, 0]
, or $2
is not specified and we still have 'leftover' values to decode.
If you still prefer to stick to a safe default such as 2
, replace n=${2:-0}
with n=${2:-2}
, and then you can drop the ||
condition.
A quick test:
$ url_decode 'You%2BWon%2527t%2BBe%252BMissed'
You+Won't+Be+Missed
$ url_decode 'You%2BWon%2527t%2BBe%252BMissed' 1
You+Won%27t+Be%2BMissed
$ url_decode 'You%2BWon%2527t%2BBe%252BMissed' 2
You+Won't+Be+Missed
As for your actual 'program', I don't see many major problems with it...