Home Explore Blog CI



nix

1st chunk of `doc/manual/source/language/string-literals.md`
8e221d63da42b943b1dcab1bcd0b42299ec4323d8936432600000001000008f9
# String literals

A *string literal* represents a [string](types.md#type-string) value.

> **Syntax**
>
> *expression* → *string*
>
> *string* → `"` ( *string_char*\* [*interpolation_element*][string interpolation] )* *string_char*\* `"`
>
> *string* → `''` ( *indented_string_char*\* [*interpolation_element*][string interpolation] )* *indented_string_char*\* `''`
>
> *string* → *uri*
>
> *string_char* ~ `[^"$\\]|\$(?!\{)|\\.`
>
> *indented_string_char* ~ `[^$']|\$\$|\$(?!\{)|''[$']|''\\.|'(?!')`
>
> *uri* ~ `[A-Za-z][+\-.0-9A-Za-z]*:[!$%&'*+,\-./0-9:=?@A-Z_a-z~]+`

Strings can be written in three ways.

The most common way is to enclose the string between double quotes, e.g., `"foo bar"`.
Strings can span multiple lines.
The results of other expressions can be included into a string by enclosing them in `${ }`, a feature known as [string interpolation].


The following must be escaped to represent them within a string, by prefixing with a backslash (`\`):

- Double quote (`"`)

> **Example**
>
> ```nix
> "\""
> ```
>
>     "\""

- Backslash (`\`)

> **Example**
>
> ```nix
> "\\"
> ```
>
>     "\\"

- Dollar sign followed by an opening curly bracket (`${`) – "dollar-curly"

> **Example**
>
> ```nix
> "\${"
> ```
>
>     "\${"

The newline, carriage return, and tab characters can be written as `\n`, `\r` and `\t`, respectively.

A "double-dollar-curly" (`$${`) can be written literally.

> **Example**
>
> ```nix
> "$${"
> ```
>
>     "$\${"

String values are output on the terminal with Nix-specific escaping.
Strings written to files will contain the characters encoded by the escaping.

The second way to write string literals is as an *indented string*, which is enclosed between pairs of *double single-quotes* (`''`), like so:

```nix
''
This is the first line.
This is the second line.
  This is the third line.
''
```

This kind of string literal intelligently strips indentation from
the start of each line. To be precise, it strips from each line a
number of spaces equal to the minimal indentation of the string as a
whole (disregarding the indentation of empty lines). For instance,
the first and second line are indented two spaces, while the third
line is indented four spaces. Thus, two spaces are stripped from
each line, so the resulting string is

Title: String Literals in Nix
Summary
This section describes string literals in Nix, covering syntax using double quotes, indented strings (using double single-quotes), and URI strings. It details escaping special characters within strings, like double quotes, backslashes, and dollar-curly braces. Indented strings automatically strip indentation, and examples are provided for clarity.