简体   繁体   中英

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''

在CentOS上,不需要额外的软件包:

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

您希望$MESSAGE用双引号引起来,因此shell不会将其拆分为单独的单词:

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

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 .

Pure Bash way:

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

echoes:

romântico

'C3 A2' is 'â' in utf8 hex

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM