How to Use Multiline Strings in YAML (with Examples)

Updated

yaml multiline string

Use | to keep line breaks and > to replace them with spaces; both quoted styles fold exactly like >. Add - (|-, >-) to drop the final newline. YAML has no multiline comment: begin every comment line with #. The parsed values:

k: |            ->  'line one\nline two\n'
  line one
  line two

k: >            ->  'line one line two\n'
  line one
  line two

k: "line one    ->  'line one line two'
  line two"

k: 'line one    ->  'line one line two'
  line two'

PyYAML 6.0.2 returned those four values, printed with repr(), and Ruby’s Psych returns the same four strings. The table lists the style to write for each result.

You want Write Value of k for two lines, a and b
Line breaks kept, one final newline | a\nb\n
Line breaks kept, no final newline |- a\nb
Long text wrapped in the file, one line in the value > a b\n
The same, without the final newline >- a b
Every trailing blank line kept |+ or >+ a\nb\n\n\n or a b\n\n\n
Short text split over two source lines "..." or '...' a b

How the four styles treat newlines, escapes and indentation

The two flow styles, single-quoted and double-quoted, do not differ from each other in how they treat newlines or continuation indentation: both fold a source newline to a space, and both ignore the indentation of continuation lines. Re-parsed cell by cell:

                     |            >            "            '
newline in source    kept         -> space     -> space     -> space
literal \n text      stays \n     stays \n     -> newline   stays \n
continuation indent  significant  significant  ignored      ignored

Row two is the only real difference between " and ': k: "a\nb" parses to 'a\nb', a two-line string, while k: 'a\nb' parses to 'a\\nb', a four-character string containing a literal backslash. Single quotes have exactly one escape, a doubled quote: k: 'it''s here' gives "it's here".

Row three was checked by re-parsing the same document with the continuation line indented 2, 6 and 10 spaces. All six results were identical: 'line one line two'. Leading whitespace on a folded continuation line is discarded in both quoted styles.

There are three chomping indicators, not two

Besides - and + there is a third, the default, which is the one you get every time you don’t type anything. It is called clip. YAML 1.2.2 §8.1.1.2 describes it this way: “the final line break character is preserved in the scalar’s content. However, any trailing empty lines are excluded from the scalar’s content.” Same block, same trailing blank lines, three indicators:

k: |     (clip, default)  ->  'a\nb\n'
k: |-    (strip)          ->  'a\nb'
k: |+    (keep)           ->  'a\nb\n\n\n'

k: >     (clip, default)  ->  'a b\n'
k: >-    (strip)          ->  'a b'
k: >+    (keep)           ->  'a b\n\n\n'

Clip is why a | block almost always ends in exactly one \n. If you are embedding a value into a shell command or an SQL string and getting a stray trailing newline, |- is the fix.

The gotcha: > does not fold indented lines

In a folded block, any line indented more than the block’s own indentation is not folded. It keeps its line break, and its extra leading spaces survive into the value. YAML 1.2.2 §6.5 (Line Folding), under “Block Folding”: “folding does not apply to line breaks surrounding text lines that contain leading white space.”

A folded SQL query is the perfect victim. Here it is with one line indented two spaces further, which is what happens the moment someone tidies up a query:

database_query: >
  SELECT user_id, username
  FROM users
    WHERE active = 1
  ORDER BY last_login DESC
'SELECT user_id, username FROM users\n  WHERE active = 1\nORDER BY last_login DESC\n'

Two embedded newlines and two leading spaces that were never meant to be data. Remove that one indent and the same block parses to a single line:

'SELECT user_id, username FROM users WHERE active = 1 ORDER BY last_login DESC\n'

SQL usually survives this, since newlines are whitespace to a query parser. A folded YAML value fed to a shell, an HTTP header, a CSV field or a single-line log format does not. Nothing warns you: both documents are valid YAML and both parse without error.

The related rule is friendlier: a blank line inside a > block becomes one newline, and two blank lines become two. 'para one\npara two\n' and 'para one\n\npara two\n' respectively.

Tabs are not indentation

k:
<tab>- a
yaml.scanner.ScannerError: while scanning for the next token
found character '\t' that cannot start any token
  in "<unicode string>", line 2, column 1

Psych raises the equivalent error. YAML 1.2.2 §6.1: “tab characters must not be used in indentation, since different systems treat tabs differently.” A tab inside a scalar is fine: k: | followed by a<tab>b parses to 'a\tb\n'. Only the leading whitespace is restricted, which is why the error can look mystifying when your editor renders the two identically.

Indentation indicators exist for one specific case

If the first line of a block is itself indented further than the rest, the parser cannot tell content from structure and gives up:

k: |
      indented first line
  second line

yaml.parser.ParserError: while parsing a block mapping ...
expected <block end>, but found '<scalar>'

Writing k: |2 declares the block indentation explicitly and the same document parses to ' indented first line\nsecond line\n'. That digit is the entire purpose of the indentation indicator.

YAML has no multiline comment

A comment in YAML starts with # and ends at the end of that line. YAML 1.2.2 §6.6 says “An explicit comment is marked by a “#” indicator”, and its Example 6.11, titled “Multi-Line Comments”, continues a comment onto a second line by starting that line with # as well. The grammar has no opening and closing marker for a block. To comment out a paragraph, put # in front of each line. For where a single # counts as a comment and where it is part of the value, see add comments in a YAML file.

# first line of the comment
# second line of the comment
k: v

yq -o=json -I0 '.'  ->  {"k":"v"}

Two tempting workarounds do not comment anything out. A # inside a block scalar is text, because the spec says comments “must not appear inside scalars”. And a block scalar under a throwaway key is real data that your program receives:

k: |
  # not a comment
  value
->  {"k":"# not a comment\nvalue\n"}

_comment: |
  this is meant to be a comment
  over two lines
k: v
->  {"_comment":"this is meant to be a comment\nover two lines\n","k":"v"}

The one place a comment may follow a block scalar indicator is the header line itself. k: | # note followed by an indented text line parses to {"k":"text\n"}; the note is dropped and the next lines are content. YAML 1.2.2 §8.1.1 calls this “the only case where a comment must not be followed by additional comment lines”.

Multiline strings in Kubernetes manifests and CI

Kubernetes reads manifests as YAML, so the same rules decide what ends up in the object. A ConfigMap value that is a whole file is written with |; the Kubernetes ConfigMap documentation says a ConfigMap “doesn’t differentiate between single line property values and multi-line file-like values”. The trailing newline is part of the value, so | and |- give different bytes:

data:
  script.sh: |
    #!/bin/sh
    echo hello
  motd: |-
    hello

yq -o=json -I0 '.data' cm.yaml
->  {"script.sh":"#!/bin/sh\necho hello\n","motd":"hello"}

The bigger trap is a container command and args, where the Kubernetes documentation runs a shell with command: ["/bin/sh"] and args: ["-c", "while true; do echo hello; sleep 10;done"]. In a manifest like the one below, with >, the lines are joined with spaces, so two commands become one. I passed each parsed argument to sh -c:

args:                      args:
- >                        - |
  echo one                   echo one
  echo two                   echo two

sh -c "$(yq -r ...)"       sh -c "$(yq -r ...)"
one echo two               one
                           two

Use | when each line is its own command, or > with explicit && or ; at the end of each line. GitHub Actions uses the same form: its workflow syntax documentation shows run: | for a multi-line command and says “each line runs in the same shell”.

Does a YAML 1.2 parser give different results?

For everything above, no. I ran 37 small documents through six parsers: PyYAML, Psych, SnakeYAML (documented as a YAML 1.1 parser), yq, ruamel.yaml (a YAML 1.2 loader) and SnakeYAML Engine (a YAML 1.2 parser). Every block and quoted case in the sections above came back byte-identical from all six, and the two error cases (tab indentation, over-indented first line) raised an error in all six. The differences were elsewhere. One matters for multiline strings: YAML 1.2.2 §5.4 says the characters next line (U+0085), line separator (U+2028) and paragraph separator (U+2029) are not line breaks, while YAML 1.1 treated them as breaks. A literal block with U+2028 between two words:

Parser (version) Result for k: | with a, U+2028, b
SnakeYAML Engine 3.2 {"k":"a\u2028b\n"}, kept as content
PyYAML 6.0.2 and 6.0.3, Psych 3.1.0, SnakeYAML 2.7, yq 4.54.1, ruamel.yaml 0.19.1 error, “while scanning a simple key” or “while parsing a block mapping”

The same split happened with U+0085 inside a > block. So the claim that YAML 1.1 and 1.2 never touch multiline scalars is wrong for these three characters: if your text can contain them, pin the parser and test. Separately, Psych on libyaml 0.2.1 rejects a %YAML 1.2 directive (“found incompatible YAML document”) while the other five accept it. Outside multiline scalars the parsers also disagree on typing: k: yes is a boolean in PyYAML, Psych and SnakeYAML, and the string yes in yq, ruamel.yaml and SnakeYAML Engine.

Tested on and not tested

I ran every example on 15 October 2026 on macOS 26.6 (arm64): PyYAML 6.0.2 on the system Python 3.9.6 and PyYAML 6.0.3 and ruamel.yaml 0.19.1 in a virtualenv, Ruby 2.6.10 with Psych 3.1.0 and libyaml 0.2.1, yq 4.54.1, and OpenJDK 17.0.20.1 with SnakeYAML 2.7 and SnakeYAML Engine 3.2. The first block of values and the folding, chomping, tab and indentation examples were re-run on all of them. The Kubernetes manifests were parsed with yq and the arguments run with sh -c; I did not run kubectl, a cluster or a GitHub Actions runner, and I did not test js-yaml, Go’s yaml.v3 outside yq, or emitting YAML.

The exact strings for the examples in the first sections and the tab error are asserted in a scratch directory by the verify script (24 checks passed on 15 October 2026); it does not cover the comment, Kubernetes or SnakeYAML cases.

Photo of author
Sudhir P. founded HeatWare.com in 1999 and has built and operated it full-stack ever since; it is now used by more than 88,000 people. He writes here about the PostgreSQL, MySQL, Linux and DevOps work that keeps it running. Articles are rewritten only after the commands in them have actually been run, and the verification scripts are published alongside them so anyone can check the claims. Reach him at blog@heatware.net.