YAML Multiline Strings: Literal and Folded Block Scalars
Master YAML multiline string syntax including literal blocks (|), folded blocks (>), and their chomping modifiers (+, -). Learn when to use each style for scripts, templates, and documentation.
Detailed Explanation
YAML Multiline Strings
YAML provides several ways to handle multiline text content. Choosing the right style is important for shell scripts, SQL queries, HTML templates, and any value that spans multiple lines.
Literal Block Scalar (|)
The pipe character preserves all line breaks exactly as written:
script: |
#!/bin/bash
echo "Hello"
if [ -f config.yml ]; then
echo "Config found"
fi
This is ideal for shell scripts, code snippets, and any content where line breaks are significant.
Folded Block Scalar (>)
The greater-than sign folds line breaks into spaces, creating flowing paragraphs:
description: >
This is a long description
that will be folded into
a single paragraph.
Result: "This is a long description that will be folded into a single paragraph.\n"
Blank lines within a folded block create actual line breaks, allowing you to separate paragraphs.
Chomping Modifiers
Both | and > support chomping modifiers that control trailing newlines:
- Clip (default) —
|or>— Single trailing newline - Strip —
|-or>-— No trailing newline - Keep —
|+or>+— Preserve all trailing newlines
# No trailing newline
message: |-
Hello World
# Preserve trailing newlines
log_entry: |+
Error occurred
Indentation Indicator
You can specify the indentation level with a number:
content: |2
This text is indented 4 spaces
but only 2 are part of the content
Quoted Multiline Strings
Double-quoted strings support escape sequences for multiline content:
message: "Line one\nLine two\nLine three"
Formatter Behavior
A good YAML formatter should:
- Preserve the block scalar style (
|vs>) chosen by the author - Maintain chomping modifiers
- Not re-indent the content of block scalars (only the indicator line)
- Handle trailing whitespace within block scalars carefully
Use Case
Multiline strings are essential in Kubernetes ConfigMaps (embedding configuration files), GitHub Actions (multi-line run commands), Ansible (template content), and Helm charts (embedded scripts). Understanding the difference between literal and folded styles prevents unexpected behavior in shell scripts and configuration templates.