如何解决docker-compose文件中的bad substitution错误并运行bash循环
解决docker-compose中的bad substitution错误及循环运行问题
问题原因
- 你使用
/bin/sh作为执行shell,但${domains[@]}是Bash独有的数组语法,POSIX标准的sh不支持该语法,这就是触发bad substitution错误的核心原因。 - 环境变量
domains的格式(x.com,y.com)不符合Bash的数组定义规则,Bash数组需要用空格分隔元素。
修正后的完整配置
environment: domains: "x.com y.com" # 改为空格分隔的字符串格式 email: your-email@example.com # 补充你的邮箱环境变量 entrypoint: - /bin/bash # 替换为Bash以支持数组等扩展语法 - -c - | curl -s https://raw.githubusercontent.com/certbot/certbot/master/certbot-nginx/certbot_nginx/_internal/tls_configs/options-ssl-nginx.conf > "/etc/letsencrypt/options-ssl-nginx.conf" echo "$$email" curl -s https://raw.githubusercontent.com/certbot/certbot/master/certbot/certbot/ssl-dhparams.pem > "/etc/letsencrypt/ssl-dhparams.pem" ls -la /etc/letsencrypt/ echo "$$domains" # 直接遍历空格分隔的域名字符串 for domain in $$domains; do echo "$$domain" done
关键调整点
- 切换执行shell:将
/bin/sh替换为/bin/bash,确保支持数组、字符串自动拆分等Bash特性。 - 修正环境变量格式:把
(x.com,y.com)改成"x.com y.com",用空格分隔域名,让Bash能自动拆分为循环元素。 - 正确转义
$符号:在docker-compose的多行脚本中,所有需要传递给shell的$必须写成$$,避免被Compose提前解析。比如$$email最终会被shell识别为环境变量$email。
可选的数组写法
如果需要明确使用数组处理,也可以先将字符串转为数组再遍历:
# 将字符串转为Bash数组 IFS=' ' read -r -a domain_array <<< "$$domains" for domain in "$${domain_array[@]}"; do echo "$$domain" done
内容的提问来源于stack exchange,提问作者user21978638
相关产品推荐
相关产品推荐

