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 $@
The question is about doing this in bash and there's no need for python or perl as there is in fact a single command that does exactly what you want - "urlencode".
This is also much better, as the above perl answer, for example, doesn't encode all characters correctly. Try it with the long dash you get from Word and you get the wrong encoding.
Note, you need "gridsite-clients" installed to provide this command.
Another php approach:
Using php from a shell script:
Use
curl --data-urlencode
; fromman curl
:Example usage:
See the man page for more info.
This requires curl 7.18.0 or newer (released January 2008). Use
curl -V
to check which version you have.For those of you looking for a solution that doesn't need perl, here is one that only needs hexdump and awk:
Stitched together from a couple of places across the net and some local trial and error. It works great!
This is the ksh version of orwellophile's answer containing the rawurlencode and rawurldecode functions (link: How to urlencode data for curl command?). I don't have enough rep to post a comment, hence the new post..