How to read file and apply substitutions to its content?

Viewed 918

I have a long string which I want to extract to a separate file.

prepare = lib.hm.dag.entryAfter ["writeBoundary"] '' very long script with ${...} '';

I can read it with builtins.readFile but it does not replace ${...} nix place holders.

How can I read string from a file and resolve nix variables inside it?

1 Answers

You could use the substitute family of bash functions (see Nixpkgs manual) or use the substituteAll Nix function which produces a derivation that performs the substitution.

substituteAll { src = ./sample.sh; inherit bash; hi = hello; }

sample.sh:

#!@bash@/bin/bash
@hi@

Result:

$ nix repl <nixpkgs>

nix-repl> substituteAll { src = ./sample.sh; inherit bash; hi = hello; }
«derivation /nix/store/7klv763a0ipgvwf3j84aazkzx2d5rljz-sample.sh.drv»

nix-repl> :b substituteAll { src = ./sample.sh; inherit bash; hi = hello; }

this derivation produced the following outputs:
  out -> /nix/store/v03hpzw9ykrbyqpmalnijnyibq3waqhw-sample.sh

nix-repl> 

/nix/store/v03hpzw9ykrbyqpmalnijnyibq3waqhw-sample.sh:

#!/nix/store/a4yw1svqqk4d8lhwinn9xp847zz9gfma-bash-4.4-p23/bin/bash
/nix/store/jmmw0d3nmklwafcwylvrjb9v69wrbcxf-hello-2.10
Related