← 中文资源

简体中文版本

Bash Here Document 与 Here String

使用 heredoc 生成 YAML 配置和可执行脚本,对比引用与未引用定界符的展开行为,并用 here string 拆分单行输入。

阅读英文原文

功能说明

脚本演示三种内联输入方式:引用定界符的 heredoc 原样写入 YAML 配置;未引用定界符的 heredoc 展开变量和命令,生成应用信息文件;here string 把一行文本拆成多个字段;还把 heredoc 传给函数逐行处理,并生成一个带执行权限的临时脚本后运行。

关键代码

  • cat > /tmp/config.yaml << 'EOF' 中定界符加引号,$ 和反引号不会被展开,适合写配置模板。
  • cat > /tmp/app.info << EOF 未加引号,因此 $app_name、$version、$(date ...) 和 $$ 都会在写入前替换。
  • read -r first second third <<< "one two three" 用 here string 把单行输入交给 read,按空白拆成三个变量。
  • process_data << EOF 把多行文本作为标准输入传给函数,函数内用 while IFS= read -r line 逐行读取。
  • 生成脚本时使用 << 'SCRIPT' 保留 $@ 字面量,之后 chmod +x 并执行,最后删除临时文件。

使用注意

定界符必须单独占一行且前面不能有空格(除非使用 <<- 并配合制表符)。引用定界符会阻止变量展开,这是生成脚本和配置时最容易混淆的地方。heredoc 内容会原样进入文件,敏感信息不要硬编码。临时文件建议使用 mktemp 并确保清理。

验证方式

执行脚本后查看 /tmp/config.yaml 中的 $ 是否保持原样,/tmp/app.info 中的变量是否已替换;确认 Parsed: one / two / three、三行函数输出以及生成脚本打印的两个参数,最后检查临时文件已被删除。

代码示例

#!/usr/bin/env bash
set -euo pipefail

# Here document: no expansion (quoted delimiter)
cat > /tmp/config.yaml << 'EOF'
server:
  host: localhost
  port: 8080
  timeout: 30

database:
  url: postgres://localhost:5432/mydb
  pool_size: 10

logging:
  level: info
  file: /var/log/app.log
EOF
echo "Config file created"

# Here document: with variable expansion
app_name="MyApp"
version="1.0.0"
cat > /tmp/app.info << EOF
Application: $app_name
Version: $version
Generated: $(date +%Y-%m-%d)
PID: $$
EOF
cat /tmp/app.info

# Here string (single line)
read -r first second third <<< "one two three"
echo "Parsed: $first / $second / $third"

# Here document to function
process_data() {
    while IFS= read -r line; do
        echo "  > $line"
    done
}

process_data << EOF
Line 1: Hello
Line 2: World
Line 3: From Bash
EOF

# Generate script from heredoc
cat > /tmp/generated.sh << 'SCRIPT'
#!/usr/bin/env bash
echo "Generated script running"
echo "Arguments: $@"
SCRIPT
chmod +x /tmp/generated.sh
/tmp/generated.sh arg1 arg2

# Cleanup
rm -f /tmp/config.yaml /tmp/app.info /tmp/generated.sh