如何仅使用BASH实现字符串urlencode解决curl传参含空格报错问题
解决方案
方案1:直接用curl自带能力自动编码(推荐,无需额外写编码逻辑)
curl原生支持--data-urlencode参数自动完成URL编码,搭配-G参数可以将编码后的参数自动拼接到URL的查询字符串中,完全不需要手动处理编码逻辑,适配所有特殊字符场景,修改你的代码中curl相关部分即可:
把原来拼在URL后的name参数从URL中移除,改为通过--data-urlencode传递,同时添加-G参数:
# 原curl语句替换为以下内容 curl --data "EntryID=123456789&tracking0=64" \ --data-urlencode "name="&userInput \ -G \ -H "user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1.1 Safari/605.1.15" \ https://secure.logmeinrescue.com/Customer/Download.aspx \ --output lmimcc.pkg.zip
逻辑说明:
-G参数会将所有--data/--data-urlencode指定的参数从请求体转为URL查询参数--data-urlencode会自动对参数值做标准URL编码,空格会自动转为%20,无需手动处理
方案2:纯Shell实现通用URL编码函数
如果需要单独对字符串做URL编码,可以使用以下纯Shell实现的函数,兼容Mac默认的Bash 3.2及Zsh环境,无需依赖Python等外部工具:
urlencode() { local string="$1" local strlen=${#string} local encoded="" local pos c o for (( pos=0 ; pos<strlen ; pos++ )); do c=${string:$pos:1} case "$c" in [-_.~a-zA-Z0-9] ) o="${c}" ;; * ) printf -v o '%%%02x' "'$c" esac encoded+="${o}" done echo "${encoded}" }
使用方法:
# 调用示例 encoded_input=$(urlencode "$userInput") # 之后直接把$encoded_input拼接到URL中即可
额外优化建议
你当前的代码中将所有Shell逻辑都写在AppleScript的do shell script中,需要注意引号的转义正确性,避免变量解析异常。如果逻辑复杂度持续提升,建议将AppleScript获取到的userInput输出到外层Shell变量中,再在外层执行后续Shell逻辑,降低转义复杂度:
#!/bin/bash # 调整后的结构示例 userInput=$(osascript -e 'set Alloyvar to "Alloy Client Connect" set myInputs to display dialog Alloyvar default answer "Company & your name" buttons {"Connect", "Cancel"} default button 1 with title "My Dialog" with icon caution set userInput to text returned of myInputs') # 之后在外层Shell处理编码、执行curl等逻辑
内容的提问来源于stack exchange,提问作者user16660683
相关产品推荐
相关产品推荐

