macOS bash 3.2.57带引号变量意外触发通配符匹配求助
解决macOS Bash 3.2.57中单引号变量通配符异常问题
正常情况(Linux Bash 5.2.15)
单引号可正常阻止通配符匹配:
$ dir='/path?/to?/file?'; echo $dir /path?/to?/file? $
异常情况(macOS Bash 3.2.57)
变量设置正确,但echo $dir时意外触发通配符匹配,导致输出为空:
$ dir='/path?/to?/file?'; echo $dir $
变量验证
确认变量已正确存储:
$ set | grep ^dir dir='/path?/to?/file?'
解决办法
输出时用双引号包裹变量:
双引号会阻止通配符扩展,同时保留变量值:$ dir='/path?/to?/file?'; echo "$dir" /path?/to?/file?使用printf命令替代echo:
printf对参数的处理更稳定,不会触发路径扩展:$ dir='/path?/to?/file?'; printf '%s\n' "$dir" /path?/to?/file?升级Bash版本:
macOS自带的Bash 3.2是较旧版本,存在诸多兼容性问题。通过包管理工具(如Homebrew)安装新版Bash(如5.x)后,即可获得和Linux一致的行为。安装后需将新版Bash添加到系统可用shell列表,并切换默认shell。
内容的提问来源于stack exchange,提问作者Bill Wohler
相关产品推荐
相关产品推荐

