URL encoding in bash with perl

ENCODED=$(echo -n "value to encode" | \
perl -pe's/([^-_.~A-Za-z0-9])/sprintf("%%%02X", ord($1))/seg');
echo $ENCODED

This command line percent-encodes strings, even binary data. You can use redirection. I used `echo -n` because I didn’t want a newline (%0A) tagged onto the end. I’ll be using this in a bash script to send HTTP POST data via curl.

My result is based on Perl URL Encode & Decode String, modified to be run on the command line and updated to skip the four non-alphanumeric unreserved characters specified in RFC 3986 Section 2.3.

I don’t know if this depends on Perl multibyte settings or anything else. I might have just been lucky. Perl isn’t my thing.

Previous Post
Leave a comment

4 Comments

  1. Troy Volin

     /  November 3, 2008

    Wow. Google for “bash function url encode” and you can’t hope for better results than this!
    Thanks!

    Reply
  2. you don’t need to do this, curl encodes the data: curl -d “option=arg”

    Reply
  3. Demiurg

     /  August 20, 2009

    perl -MURI::Escape -e ‘print uri_escape(“=+%”) . “\n”‘

    Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 1,665 other followers

%d bloggers like this: