Sample Header Ad - 728x90

urlencode function

7 votes
3 answers
15170 views
I need a way to URL encode strings with a shell script on a OpenWRT device running old version of busybox. Right now I ended up with the following code: urlencode() { echo "$@" | awk -v ORS="" '{ gsub(/./,"&\n") ; print }' | while read l do c="echo "$l" | grep '[^-._~0-9a-zA-Z]'" if [ "$l" == "" ] then echo -n "%20" else if [ -z "$c" ] then echo -n "$l" else printf %%%02X \'"$c" fi fi done echo "" } This works more or less fine but there're a few flaws: 1. Some characters are skipped, like "\", for example. 2. Result is return character by character so it's extremely slow. It takes about 20 seconds to url encode just a few strings inside a batch. My version of bash doesn't support substring like this ${var:x:y}.
Asked by Serg (173 rep)
Jan 8, 2013, 05:35 PM
Last activity: Apr 21, 2024, 05:26 PM