I am trying to write a bash script for testing that takes a parameter and sends it through curl to web site. I need to url encode the value to make sure that special characters are processed properly. What is the best way to do this?
Here is my basic script so far:
#!/bin/bash
host=${1:?'bad host'}
value=$2
shift
shift
curl -v -d "param=${value}" http://${host}/somepath $@
for the sake of completeness, many solutions using
sed
orawk
only translate a special set of characters and are hence quite large by code size and also dont translate other special characters that should be encoded.a safe way to urlencode would be to just encode every single byte - even those that would've been allowed.
xxd is taking care here that the input is handled as bytes and not characters.
edit:
xxd comes with the vim-common package in Debian and I was just on a system where it was not installed and I didnt want to install it. The altornative is to use
hexdump
from the bsdmainutils package in Debian. According to the following graph, bsdmainutils and vim-common should have an about equal likelihood to be installed:http://qa.debian.org/popcon-png.php?packages=vim-common%2Cbsdmainutils&show_installed=1&want_legend=1&want_ticks=1
but nevertheless here a version which uses
hexdump
instead ofxxd
and allows to avoid thetr
call:Here is the pure BASH answer.
You can use it in two ways:
[edited]
Here's the matching rawurldecode() function, which - with all modesty - is awesome.
With the matching set, we can now perform some simple tests:
And if you really really feel that you need an external tool (well, it will go a lot faster, and might do binary files and such...) I found this on my OpenWRT router...
Where url_escape.sed was a file that contained these rules:
If you wish to run
GET
request and use pure curl just add--get
to @Jacob's solution.Here is an example:
Here's the node version:
Having php installed I use this way:
If you don't want to depend on Perl you can also use sed. It's a bit messy, as each character has to be escaped individually. Make a file with the following contents and call it
urlencode.sed
To use it do the following.
This will split the string into a part that needs encoding, and the part that is fine, encode the part that needs it, then stitches back together.
You can put that into a sh script for convenience, maybe have it take a parameter to encode, put it on your path and then you can just call:
source