EOF区块中的Bash EOF区块可能吗?

问题描述

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

cat > terragrunt.hcl <<'EOF' 
# Automatically generated from script $(basename $0)

# 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 $0)
EOF

如预期的那样失败:

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

什么是最好的解决方案?

解决方法

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

heredoc包含与其匹配的定界符有关的所有内容,因此嵌套两个heredocs仅是选择两个不同定界符的情况:

cat > terragrunt.hcl <<'ENDTERRAGRUNT' 
# Automatically generated from script $(basename $0)

# 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 $0)
ENDTERRAGRUNT