Bash EOF 块中的 EOF 块可能吗?

Bash EOF block in EOF block possible?

我正在尝试在文件中写入一个包含其自己的 EOF 块的块。在 bash 中可行吗?

cat > terragrunt.hcl <<'EOF' 
# Automatically generated from script $(basename [=11=])

# Generate the AWS provider block
generate "provider" {
  path      = "provider.tf"
  if_exists = "overwrite_terragrunt"
  contents  = <<EOF
# Terragrunt root config
provider "aws" {
  # Only these AWS Account IDs may be operated on by this template
  allowed_account_ids = ["${local.account_id}"]
  region = "${local.infra_region}"
  version = "${local.customer_vars.locals.aws_provider_version}"
}
EOF
}

# Automatically generated from script $(basename [=11=])
EOF

正如预期的那样失败了:

❯ ./example.sh 
./example.sh: line 17: syntax error near unexpected token `}'
./example.sh: line 17: `}'

处理它的最佳解决方案是什么?

你所说的“EOF 块”实际上叫做 "Here Document"(通常缩写为“heredoc”),字符串“EOF”实际上可以是你喜欢的任何“单词”。

heredoc 包含匹配分隔符之前的所有内容,因此嵌套两个 heredoc 只是选择两个不同分隔符的情况:

cat > terragrunt.hcl <<'ENDTERRAGRUNT' 
# Automatically generated from script $(basename [=10=])

# Generate the AWS provider block
generate "provider" {
  path      = "provider.tf"
  if_exists = "overwrite_terragrunt"
  contents  = <<ENDROOTCONFIG
# Terragrunt root config
provider "aws" {
  # Only these AWS Account IDs may be operated on by this template
  allowed_account_ids = ["${local.account_id}"]
  region = "${local.infra_region}"
  version = "${local.customer_vars.locals.aws_provider_version}"
}
ENDROOTCONFIG
}

# Automatically generated from script $(basename [=10=])
ENDTERRAGRUNT