Using to curl to do urlencode in bash script
Balakrishnan Balasubramanian via curl-users <[email protected]>
| Newsgroups | gmane.comp.web.curl.general |
|---|---|
| Message-ID | <[email protected]> |
In a bash script, I want to generate a url whose query parameters need
to be url-encoded. I have the following helper function:
gen_iv () {
rhash=$1
url=$2
python3 <(: <<- EOS
from urllib.parse import urlencode
query = urlencode({"url": "$url", "rhash": "$rhash"})
print(f'https://t.me/iv?{query}')
EOS
)
}
I am trying to get rid of python dependency. I found solutions online
using awk, perl, jq. But all of them adds a dependency.
Hacked a below curl solution:
gen_iv_curl () {
rhash=$1
url=$2
(
curl -s -w '%{url}\n' --url-query "url=$url"
--url-query "rhash=$rhash" "http://127.0.0.1:0/iv" | sed
's!^http://127.0.0.1:0!https://t.me!'
) || true
}
❯ gen_iv_curl feb0cb1f19cbc2
"https://daniel.haxx.se/blog/2022/12/23/the-curl-fragment-trick/"
https://t.me/iv?url=https%3a%2f%2fdaniel.haxx.se%2fblog%2f2022%2f12%2f23%2fthe-curl-fragment-trick%2f&rhash=feb0cb1f19cbc2
Seems to work fine but have some questions:
1. Is there a better/cleaner way to do this without extra dependency?
(No pure bash hack unless readable/bug free)
2. Are there any cases where this may not work?
3. Is it ok to rely on current curl behavior? In particular, does `-w`
guaranteed to work and print the url even if curl command fails? Or
could this change in future curl versions?
------------------------------------------------------------------------
--
Unsubscribe: https://lists.haxx.se/listinfo/curl-users
Etiquette: https://curl.se/mail/etiquette.html