You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Bash脚本URL解码问题:部分编码字符串未被正确解码

URL解码脚本的问题与修复

我参考Stack Overflow的回答编写了以下Bash脚本,用于解码文本文件中的URL编码字符串:

function urldecode() { : "${*//+/ }"; echo -e "${_//%/\x}"; }
input="temp.txt"
while IFS= read -r line
do
  eval urldecode "$line"
done < "$input"

遇到的问题:foo%20bar可以正常解码为foo bar,但http%3A%2F%2F无法被解码。这两种字符串都存在于文件的多行中,且单独在终端执行单行内容时解码完全正常。

问题原因

问题出在eval命令上。当行内容包含%3A(对应冒号:)、%2F(对应斜杠/)这类字符时,eval会将它们当作Shell语法的一部分解析,导致urldecode函数接收到的参数被错误拆分或转义,最终解码失败。

修复方案

去掉eval,直接调用函数并使用双引号包裹$line,确保整行内容作为单个参数传递给函数:

function urldecode() { : "${*//+/ }"; echo -e "${_//%/\x}"; }
input="temp.txt"
while IFS= read -r line
do
  urldecode "$line"
done < "$input"

如果需要更好的兼容性(避免部分环境中echo -e的行为差异),可以改用printf实现解码:

function urldecode() {
  local encoded="${*//+/ }"
  printf '%b' "${encoded//%/\x}"
}
input="temp.txt"
while IFS= read -r line
do
  urldecode "$line"
done < "$input"

内容的提问来源于stack exchange,提问作者Daniel Franco

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 12:08:13