How to add a newly built package to PATH?

I built a simple “Hello, World package”, using nix-build -A khello. The executable ends up in result/bin/khello, so I can run it specifying the full path. However, how can I add this package to PATH, so that I can call it with khello?

# khello
khello: command not found

# ./result/bin/khello
Hello, World!

The files

builder.sh

source $stdenv/setup

mkdir -p $out/bin

cat >$out/bin/khello <<EOF
#!$SHELL
echo "Hello, World!"
EOF

chmod +x $out/bin/khello

default.nix

let
    nixpkgs = fetchTarball "https://github.com/NixOS/nixpkgs/tarball/nixos-23.11";
    pkgs = import nixpkgs { config = {}; overlays = []; };
in
{
    khello = pkgs.callPackage ./khello.nix { };
}

khello.nix

{ stdenv }:

stdenv.mkDerivation {
    name = "khello";
    builder = ./builder.sh;
}

OK, after trying different things I have manged to achieve what I wanted. However, it feels “off” doing it this way, so hopefully there is a better way. Anyway, this is what I did:

I had to create a symlink from .nix-defexpr to my package directory (it did not work using the package root, so possibly every package dir has to be linked up in a similar way):
ln -s /home/.pkgs/khello /root/.nix-defexpr/pkgs_khello

I had to build using nix-env instead of nix-build (what is the difference?):
nix-env -iA pkgs_khello.khello

Then, a new generation was created (nix-env --list-generations) and khello was “available on the PATH”, or: a symlink from ~/.nix-profiles/bin/ was created pointing to the khello binary.

Using nix-env to install might even be wrong when using Flakes. However, doing it this way seems to work.

1 Like