[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: URL encode in bash
From: |
Lawrence Velázquez |
Subject: |
Re: URL encode in bash |
Date: |
Tue, 30 Mar 2021 01:42:44 -0400 |
User-agent: |
Cyrus-JMAP/3.5.0-alpha0-273-g8500d2492d-fm-20210323.002-g8500d249 |
On Mon, Mar 29, 2021, at 11:39 PM, Peng Yu wrote:
> Hi,
>
> https://gist.github.com/cdown/1163649
>
> I see a bash program is shown above for URL encode. But I am not sure
> if it works correctly.
It does not work correctly as is, no. It needs a bit of encouragement.
bash-5.1$ curl -s
'https://gist.githubusercontent.com/cdown/1163649/raw/c3a30da93e94828918dcf3918e995726f445fc25/gistfile1.sh'
| tee /tmp/urlencode.bash; echo
urlencode() {
# urlencode <string>
old_lc_collate=$LC_COLLATE
LC_COLLATE=C
local length="${#1}"
for (( i = 0; i < length; i++ )); do
local c="${1:$i:1}"
case $c in
[a-zA-Z0-9.~_-]) printf '%s' "$c" ;;
*) printf '%%%02X' "'$c" ;;
esac
done
LC_COLLATE=$old_lc_collate
}
urldecode() {
# urldecode <string>
local url_encoded="${1//+/ }"
printf '%b' "${url_encoded//%/\\x}"
}
bash-5.1$ . /tmp/urlencode.bash
bash-5.1$ urlencode α; echo
%3B1
bash-5.1$ LC_CTYPE=C urlencode α; echo
%CE%B1
It's not clear to me why the author set LC_COLLATE instead of LC_CTYPE.
vq