The standard environment provides a number of useful functions.
substitute
infile
outfile
subs
Performs string substitution on the contents of
infile
, writing the result to
outfile
. The substitutions in
subs
are of the following form:
--replace
s1
s2
Replace every occurence of the string
s1
by
s2
.
--subst-var
varName
Replace every occurence of
@
by
the contents of the environment variable
varName
@varName
. This is useful for
generating files from templates, using
@
in the
template as placeholders....
@
--subst-var-by
varName
s
Replace every occurence of
@
by
the string varName
@s
.
Example:
substitute ./foo.in ./foo.out \ --replace /usr/bin/bar $bar/bin/bar \ --replace "a string containing spaces" "some other text" \ --subst-var someVar
substitute
is implemented using the
replace
command. Unlike with the sed command, you
don’t have to worry about escaping special characters. It
supports performing substitutions on binary files (such as
executables), though there you’ll probably want to make sure
that the replacement string is as long as the replaced
string.
substituteInPlace
file
subs
Like substitute
, but performs
the substitutions in place on the file
file
.
substituteAll
infile
outfile
Replaces every occurence of
@
, where
varName
@varName
is any environment variable, in
infile
, writing the result to
outfile
. For instance, if
infile
has the contents
#! @bash@/bin/sh PATH=@coreutils@/bin echo @foo@
and the environment contains
bash=/nix/store/bmwp0q28cf21...-bash-3.2-p39
and
coreutils=/nix/store/68afga4khv0w...-coreutils-6.12
,
but does not contain the variable foo
, then the
output will be
#! /nix/store/bmwp0q28cf21...-bash-3.2-p39/bin/sh PATH=/nix/store/68afga4khv0w...-coreutils-6.12/bin echo @foo@
That is, no substitution is performed for undefined variables.
Environment variables that start with an uppercase letter or an
underscore are filtered out,
to prevent global variables (like HOME
) or private
variables (like __ETC_PROFILE_DONE
) from accidentally
getting substituted.
The variables also have to be valid bash “names”, as
defined in the bash manpage (alphanumeric or _
,
must not start with a number).
substituteAllInPlace
file
Like substituteAll
, but performs
the substitutions in place on the file
file
.
stripHash
path
Strips the directory and hash part of a store
path, storing the name part in the environment variable
strippedName
. For example:
stripHash "/nix/store/9s9r019176g7cvn2nvcw41gsp862y6b4-coreutils-8.24" # prints coreutils-8.24 echo $strippedName
If you wish to store the result in another variable, then the following idiom may be useful:
name="/nix/store/9s9r019176g7cvn2nvcw41gsp862y6b4-coreutils-8.24" someVar=$(stripHash $name; echo $strippedName)