Bash脚本创建配置文件报错Bad Substitution的原因与解决方法
Bash脚本生成config.yml时出现"bad substitution"错误
错误信息
line 2: filebeat.inputs: - type: filestream id: my-filestream-id enabled: true : bad substitution
问题脚本
#!/bin/bash cat > "config.yml" <<EOF filebeat.inputs: - type: filestream id: my-filestream-id enabled: true paths: - /home/ubuntu/logs/**/*.log filebeat.config.modules: # Glob pattern for configuration loading path: ${path.config}/modules.d/*.yml reload.enabled: false setup.template.settings: index.number_of_shards: 1 setup.kibana: output.logstash: hosts: ["10.09.0.2:5044"] processors: - add_host_metadata: when.not.contains.tags: forwarded - add_cloud_metadata: ~ - add_docker_metadata: ~ - add_kubernetes_metadata: ~ EOF
错误原因
Bash会自动解析<<EOF格式here-doc里的变量,而你写的${path.config}不符合Bash变量命名规则(变量名仅允许字母、数字、下划线,不能包含.),导致Bash无法识别该语法,抛出"bad substitution"错误。
解决方法
有两种简单修复方式:
方法1:用单引号包裹EOF,关闭变量解析
将脚本中的<<EOF改为<<'EOF',这样Bash会原样输出here-doc内的所有内容,不再解析任何变量:
#!/bin/bash cat > "config.yml" <<'EOF' filebeat.inputs: - type: filestream id: my-filestream-id enabled: true paths: - /home/ubuntu/logs/**/*.log filebeat.config.modules: # Glob pattern for configuration loading path: ${path.config}/modules.d/*.yml reload.enabled: false setup.template.settings: index.number_of_shards: 1 setup.kibana: output.logstash: hosts: ["10.09.0.2:5044"] processors: - add_host_metadata: when.not.contains.tags: forwarded - add_cloud_metadata: ~ - add_docker_metadata: ~ - add_kubernetes_metadata: ~ EOF
方法2:转义变量符号,让Bash忽略解析
把${path.config}修改为\${path.config},通过反斜杠转义$符号,让Bash将其视为普通字符串输出:
#!/bin/bash cat > "config.yml" <<EOF filebeat.inputs: - type: filestream id: my-filestream-id enabled: true paths: - /home/ubuntu/logs/**/*.log filebeat.config.modules: # Glob pattern for configuration loading path: \${path.config}/modules.d/*.yml reload.enabled: false setup.template.settings: index.number_of_shards: 1 setup.kibana: output.logstash: hosts: ["10.09.0.2:5044"] processors: - add_host_metadata: when.not.contains.tags: forwarded - add_cloud_metadata: ~ - add_docker_metadata: ~ - add_kubernetes_metadata: ~ EOF
内容的提问来源于stack exchange,提问作者eme
相关产品推荐
相关产品推荐

