在 bash 脚本中对字符串进行 URL 编码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11876353/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
URL encoding a string in bash script
提问by Greg Alexander
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
我正在编写一个 bash 脚本,我试图在其中提交一个 post 变量,但是 wget 将它视为多个 URL 我相信因为它不是 URLENCODED ......这是我的基本想法
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
我收到错误,alert.php 没有得到 post 变量加上它几乎说
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:
我上面的例子是一个简单的 sudo 例子,但我相信如果我可以对它进行 url 编码,它就会通过,我什至尝试过像这样的 php:
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?
但是 php 出错了.. 有什么想法吗?如何在 $MESSAGE 中传递变量而不用 php 执行它?
采纳答案by Gordon Davisson
You want $MESSAGEto be in double-quotes, so the shell won't split it into separate words:
您希望$MESSAGE使用双引号,因此 shell 不会将其拆分为单独的单词:
ENCODEDMESSAGE=$(php -r "echo urlencode(\"$MESSAGE\");")
回答by Rockallite
On CentOS, no extra package needed:
在 CentOS 上,不需要额外的包:
python -c "import urllib;print urllib.quote(raw_input())" <<< "$message"
回答by Murphy
Extending Rockallite's very helpful answerfor Python 3 and multiline input from a file (this time on Ubuntu, but that shouldn't matter):
扩展Rockallite对 Python 3 和文件中的多行输入非常有用的答案(这次是在 Ubuntu 上,但这无关紧要):
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.
这将导致文件中的所有行连接成一个 URL,换行符被替换为%0A.
回答by Roger
Pure Bash way:
纯 Bash 方式:
URL='rom%C3%A2ntico'
echo -e "${URL//%/\x}"
echoes:
回声:
romantico
'C3 A2' is 'a' in utf8 hex
'C3 A2' 是 utf8 十六进制中的 'a'
utf8 list: http://www.utf8-chartable.de/
utf8 列表:http: //www.utf8-chartable.de/

