Skip to main content
0 reactions

How to Write a Comment in YAML

Card titled Comments in YAML, labelled YAML basics, with four ticked lines: a comment line, a note after the name value, a switched-off debug line that is skipped, and color with #ff0000 read as null.

A comment in a YAML file is a note for people. It starts with # and runs to the end of the line, and programs that read the file skip it. Use it to explain a setting or to switch one off.

Every command and output on this page is real, run with yq 4.54.3 on macOS.

Syntax

SyntaxYAML
# a comment on its own line
key: value  # a comment after a value
  • #: starts the comment. Everything after it on the same line is skipped.
  • After a value, put at least one space before #. Without the space, # is part of the value, as in a web address.
  • A comment ends with its line. Start each comment line with its own #.

See Comments (opens in a new tab) in the YAML 1.2.2 specification.

Prerequisites

The Example

Settings for a notes app in a file named app.yml, with a comment line, a note after a value and a switched-off setting.

Step 1: Write the YAML

app.ymlYAML
# Settings for the notes app
name: Notes   # shown in the title bar
port: 8080
# debug: true

Step 2: Read It as JSON

yq -o=json reads the file and prints its data as JSON, which has no comments, so you see exactly what a program gets:

TerminalBash
yq -o=json . app.yml
OutputJSON
{
  "name": "Notes",
  "port": 8080
}

Only name and port are in the data. The comments are gone, and debug isn’t a setting at all, because its line starts with #.

Common Mistakes

MistakeWhat happensDo this instead
A value that starts with #, such as color: #ff0000The # after the space starts a comment, so color is empty: yq gives "color": nullPut the value in quotes: color: '#ff0000'

FAQ

Does a # inside a web address start a comment?

No. A # starts a comment only at the start of a line or after a space, so link: https://example.com/#top keeps the whole address.

Conclusion

Start a comment with #, on its own line or after a space. Put a value that begins with # in quotes.

Additional Resources

0 comments