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 $@
Use Perl's
URI::Escape
module anduri_escape
function in the second line of your bash script:Edit: Fix quoting problems, as suggested by Chris Johnsen in the comments. Thanks!
This may be the best one:
Simple PHP option:
One of variants, may be ugly, but simple:
Here is the one-liner version for example (as suggested by Bruno):
Here is a POSIX function to do that:
Example:
Source
I find it more readable in python:
the triple ' ensures that single quotes in value won't hurt. urllib is in the standard library. It work for exampple for this crazy (real world) url: