URL encoding a string in bash script

I am writing a bash script where I am trying to send a post variable, but wget treats it as several URLs, which I consider because it is not URLENCODED ... here is my main idea

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

I get errors and alert.php does not receive the post variable plus it pretty mush says

cannot solve I cannot solve; cannot solve the problem .. etc.

My example above is a simple sudo example, but I believe that if I can encode it, it will pass, I even tried php, for example:

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

but php errors .. any ideas? How to pass a variable to $ MESSAGE without executing php?

+8
source share
4 answers

You want $MESSAGE be in double quotes, so the shell will not separate it into separate words:

 ENCODEDMESSAGE=$(php -r "echo urlencode(\"$MESSAGE\");") 
+4
source

There is no additional package on CentOS:

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

The Rockallite extension is a very useful answer for Python 3 and multi-line input from a file (this time in Ubuntu, but that shouldn't matter):

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

Pure bash method:

 URL='rom%C3%A2ntico' echo -e "${URL//%/\\x}" 

echoes:

 romântico 

'C3 A2' is 'â' in utf8 hex

Utf8 list: http://www.utf8-chartable.de/

-one
source

All Articles