在bash脚本中编码字符串的URL

Gre*_*der 8 linux bash command-line wget urlencode

我正在写一个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''
Run Code Online (Sandbox Code Playgroud)

我收到错误并且alert.php没有得到post变量加上它很难说

无法解决我无法解决我无法解决尝试..等等.

我上面的例子是一个简单的有点sudo示例,但我相信如果我可以对其进行url编码,它会通过,我甚至尝试过像:

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

但PHP错误..任何想法?如何在没有php执行的情况下传递$ MESSAGE中的变量?

Roc*_*ite 7

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

python -c "import urllib;print urllib.quote(raw_input())" <<< "$message"
Run Code Online (Sandbox Code Playgroud)

  • Python 3 版本看起来像 `python3 -c "import urllib.parse; print(urllib.parse.quote(input())"`。 (3认同)
  • 此解决方案仅适用于 python 2 (2认同)
  • 正确的 Python 3 版本看起来像 `python3 -c "import urllib.parse; print(urllib.parse.quote(input()))"`(这次测试)。 (2认同)

Gor*_*son 5

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

ENCODEDMESSAGE=$(php -r "echo urlencode(\"$MESSAGE\");")
Run Code Online (Sandbox Code Playgroud)


Mur*_*phy 5

扩展Rockallite对 Python 3 和文件中的多行输入非常有用的答案(这次是在 Ubuntu 上,但这无关紧要):

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

这将导致文件中的所有行连接成一个 URL,换行符被替换为%0A.

  • 不,这不起作用。将“sys.stdin.read()”替换为“input()”。使用“read()”添加“%0A”,这是文件终止符。 (2认同)