Greg Alexander
Greg Alexander

Reputation: 1222

URL encoding a string in bash script

I am writing a bash script in where I am trying to submit a post variable, however wget is treating it as multiple URLS I believe because it is not URLENCODED... here is my basic thought

MESSAGE='I am trying to post this information'
wget -O test.txt http://xxxxxxxxx.com/alert.php --post-data 'key=xxxx&message='$MESSAGE''

I am getting errors and the alert.php is not getting the post variable plus it pretty mush is saying

can't resolve I can't resolve am can't resolve trying .. and so on.

My example above is a simple kinda sudo example but I believe if I can url encode it, it would pass, I even tried php like:

MESSAGE='I am trying to post this information'
MESSAGE=$(php -r 'echo urlencode("'$MESSAGE'");')

but php errors out.. any ideas? How can i pass the variable in $MESSAGE without php executing it?

Upvotes: 15

Views: 43350

Answers (3)

Gordon Davisson
Gordon Davisson

Reputation: 125798

You want $MESSAGE to be in double-quotes, so the shell won't split it into separate words, then pass it to PHP as an argument:

ENCODEDMESSAGE="$(php -r 'echo rawurlencode($argv[1]);' -- "$MESSAGE")"

Upvotes: 9

Murphy
Murphy

Reputation: 3999

Extending Rockallite's very helpful answer for Python 3 and multiline input from a file (this time on Ubuntu, but that shouldn't matter):

cat any.txt | python3 -c "import urllib.parse, sys; print(urllib.parse.quote(sys.stdin.read()))"

This will result in all lines from the file concatenated into a single URL, the newlines being replaced by %0A.

Upvotes: 6

Rockallite
Rockallite

Reputation: 16935

On CentOS, no extra package needed:

python -c "import urllib;print urllib.quote(raw_input())" <<< "$message"

Upvotes: 18

Related Questions