1# Build Support {#sec-build-support} 2 3## `pkgs.substitute` {#pkgs-substitute} 4 5`pkgs.substitute` is a wrapper around [the `substitute` Bash function](#fun-substitute) in the standard environment. 6It replaces strings in `src` as specified by the `substitutions` argument. 7 8 9:::{.example #ex-pkgs-substitute} 10# Usage of `pkgs.substitute` 11 12In a build script, the line: 13 14```bash 15substitute $infile $outfile --replace-fail @foo@ ${foopkg}/bin/foo 16``` 17 18is equivalent to: 19 20```nix 21{ substitute, foopkg }: 22substitute { 23 src = ./sourcefile.txt; 24 substitutions = [ 25 "--replace" 26 "@foo@" 27 "${foopkg}/bin/foo" 28 ]; 29} 30``` 31::: 32 33## `pkgs.replaceVars` {#pkgs-replacevars} 34 35`pkgs.replaceVars <src> <replacements>` replaces all instances of `@varName@` (`@`s included) in file `src` with the respective value in the attribute set `replacements`. 36 37:::{.example #ex-pkgs-replace-vars} 38# Usage of `pkgs.replaceVars` 39 40If `say-goodbye.sh` contains the following: 41 42```bash 43#! @bash@/bin/bash 44 45echo @unchanged@ 46@hello@/bin/hello --greeting @greeting@ 47``` 48 49the following derivation will make substitutions to `@bash@`, `@hello@`, and `@greeting@`: 50 51```nix 52{ 53 replaceVars, 54 bash, 55 hello, 56}: 57replaceVars ./say-goodbye.sh { 58 inherit bash hello; 59 greeting = "goodbye"; 60 unchanged = null; 61} 62``` 63 64such that `$out` will result in something like the following: 65 66``` 67#! /nix/store/s30jrpgav677fpc9yvkqsib70xfmx7xi-bash-5.2p26/bin/bash 68 69echo @unchanged@ 70/nix/store/566f5isbvw014h7knmzmxa5l6hshx43k-hello-2.12.1/bin/hello --greeting goodbye 71``` 72 73Note that, in contrast to the old `substituteAll`, `unchanged = null` must explicitly be set. 74Any unreferenced `@...@` pattern in the source file will throw an error. 75::: 76 77## `pkgs.replaceVarsWith` {#pkgs-replacevarswith} 78 79`pkgs.replaceVarsWith` works the same way as [pkgs.replaceVars](#pkgs-replacevars), but additionally allows more options. 80 81:::{.example #ex-pkgs-replace-vars-with} 82# Usage of `pkgs.replaceVarsWith` 83 84With the example file `say-goodbye.sh`, consider: 85 86```nix 87{ replaceVarsWith }: 88replaceVarsWith { 89 src = ./say-goodbye.sh; 90 91 replacements = { 92 inherit bash hello; 93 greeting = "goodbye"; 94 unchanged = null; 95 }; 96 97 name = "say-goodbye"; 98 dir = "bin"; 99 isExecutable = true; 100 meta.mainProgram = "say-goodbye"; 101} 102``` 103 104This will make the resulting file executable, put it in `bin/say-goodbye` and set `meta` attributes respectively. 105:::