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

如何在Dockerfile RUN指令中转义含特殊字符和单引号的字符串并写入.bashrc

最优解决方案:使用Here Document写入(无需额外转义)

直接在Dockerfile的RUN指令中使用带单引号包裹终止符的Here Document,内容会完全原样写入目标文件,不需要处理任何转义:

RUN cat >> /home/local-user/.bashrc <<'EOF'
bind '"\e[A": history-search-backward'
bind '"\e[B": history-search-forward'
EOF

这里<<'EOF'的单引号是关键,它会禁用shell对heredoc内部内容的变量展开、转义符解析,完全保留原始字符串格式。


可选方案:逐行echo写法

如果你坚持用逐行echo的方式,用单引号包裹输出内容,内部的单引号用'\''格式转义即可:

RUN echo 'bind '\''"\e[A": history-search-backward'\' >> /home/local-user/.bashrc \
 && echo 'bind '\''"\e[B": history-search-forward'\' >> /home/local-user/.bashrc

内容的提问来源于stack exchange,提问作者The Fool

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 11:54:03