Daniil Iaitskov
Daniil Iaitskov

Reputation: 6049

Isolated temporary files in Nix derivation

I haven't found any info about handling temporary files in Nix derivations.

I found $TMP and $TMPDIR env vars, but they both point just to /tmp, which is system global.

{
  pkgs ? import <nixpkgs> {}
}:
  pkgs.stdenv.mkDerivation {
    pname = "show-tmp"
    version = "0.1.0";
    src = ./.;
    configurePhase = ''
      echo "tmp = $tmp; TMP =  $TMP; TMPDIR = $TMPDIR"
    '';
    buildPhase = '':'';
    installPhase = '':'';        
  }

Variable $tmp is not defined inside mkDerivation. I would expect such thing, because other derivation scope vars follow low case style such as $out.

The problem with /tmp is obvious - it is global directory. I need to worry about collisions and cleaning.

My derivation-hook archives a big folder tree.

Upvotes: 3

Views: 2120

Answers (1)

Robert Hensing
Robert Hensing

Reputation: 7369

If you're on Linux, don't worry. The Nix sandbox will give your build its own empty /tmp. It is removed when your derivation is done.

On macOS, $TMP and $TMPDIR are taken care of but /tmp is a potential problem.

How Nix creates a private /tmp on Linux


macOS Darwin, where Nix was installed in early 2020:

nix-build --expr 'with import <nixpkgs> {}; runCommand "hi" {} "echo a > /tmp/a; ls -al /tmp; sleep 1;"'
ls -al /private/tmp/
...
-rw-r--r--  1 nixbld1  wheel    2 May 19 12:49 a
...

Upvotes: 3

Related Questions