Nix: Outputting '${ from indented strings

Created on 20 Jun 2017  Â·  4Comments  Â·  Source: NixOS/nix

It seems impossible to output a '${ string (escaped) from indented strings.


Examples:

Unescaped is evaluated, as expected:

nix-repl> '' (${x}) ''
error: undefined variable ‘x’ at (string):1:7

Correctly escaped with '':

nix-repl> '' (''${x}) ''
"(${x}) "

Trying to add a ' in front of escaped ${, the first ''' are processed as escaped '' and ${ is not escaped:

nix-repl> '' ('''${x}) ''
error: undefined variable ‘x’ at (string):1:10

Adding another ' process the first ''' as '' and the following '${ as unescaped:

nix-repl> '' (''''${x}) ''
error: undefined variable ‘x’ at (string):1:11

Adding another ' process the first ''' as '' and the following ''${ is escaped to ${:

nix-repl> '' ('''''${x}) ''
"(''${x}) "

Is there a way to output strings like "('${x})" from indented strings?

Most helpful comment

Indentend strings have a generic escaping mechanism — ''\., so you can write '${ as ''\'''\$''\{ or, more practically, as '$''\{.

All 4 comments

Just noticed this, but for anyone stuck right now, I hacked it together as follows:

let
  foo = ''
    echo '${"\${zomg}"}'
  '';
in foo

Basically, I just gave up trying to escape it in the double single quote context so I actually "escaped" the context and did it in a different string 😄

Indentend strings have a generic escaping mechanism — ''\., so you can write '${ as ''\'''\$''\{ or, more practically, as '$''\{.

I think this can be closed, allthough the example and answer by @orivej here would be a nice addition to the docs imho.

Inspired by @copumpkin, I made a general escaping function escape = content: "$\{" + content + "}";. With this, you can produce '${} by '${escape ""}, and in the more general case use it with ${escape "content"} within any multiline strings.

Please don't close this as long as this issue is the primary source for information; this really should be mentioned in the docs.

Was this page helpful?
0 / 5 - 0 ratings