在bash中解码URL

Jui*_*icy 2 url bash cgi sed web

我试图在纯粹的bash中解码GET参数.

即:hello+%26+world应该成为hello & world

到目前为止,我已经设法得到这个:

#!/usr/bin/sh
echo "Content-type: text/plain"
echo ""

CMD=`echo "$QUERY_STRING" | grep -oE "(^|[?&])cmd=[^&]+" | sed "s/%20/ /g" | cut -f 2 -d "="`
CMD="${CMD//+/ }"

echo $CMD
Run Code Online (Sandbox Code Playgroud)

+用空格取代所有空间.

有一个更好的方法吗?或者我只需要查找每个可能的编码特殊字符并替换它?

anu*_*ava 7

您可以使用此功能进行URL解码:

decodeURL() { printf "%b\n" "$(sed 's/+/ /g; s/%\([0-9a-f][0-9a-f]\)/\\x\1/g;')"; }
Run Code Online (Sandbox Code Playgroud)

然后将其测试为:

decodeURL <<< 'hello+%26+world'
hello & world
Run Code Online (Sandbox Code Playgroud)

说明:

  • printf %b - 在相应的参数中展开反斜杠转义序列
  • s/+/ /g- 用+空格替换每个
  • s/%\([0-9a-f][0-9a-f]\)/\\x\1/g- 用%文字\x和相同的十六进制字符替换每个后跟2个十六进制字符,以便printf为它打印等效的ASCII字符

  • 我还必须匹配大写十六进制字符:`s /%\([0-9a-fA-F] [0-9a-fA-F] \)/ \\ x \ 1 / g` (2认同)