Eval Nix expression from the command line?

I can always

❯ nix repl '<nixpkgs>'               
Welcome to Nix version 2.3.7. Type :? for help.

Loading '<nixpkgs>'...
Added 12433 variables.

nix-repl> vscode.version

But is it possible to pass the expression vscode.version as a CLI argument for easier scripting?

I’m ideally looking for something like nix repl '<nixpkgs>' --expr 'vscode.version'.


Answering my own question:

❯ nix eval -f '<nixpkgs>' 'vscode.version'

That’s fantastic – but how would you discover the src.url for a derivation?


FooBar = super.mkDerivation rec {
  src = super.fetchurl {
    url = “http://example.com/${version}/foobar.zip”;
    sha256 = “xxxxxxx”;

I’d love to discover the sha256 of an available to update to by doing this on the shell:

% (version=“12.12.1”; url=$(nix eval -f ‘<nixpkgs’ ‘FooBar.src.url’); nix-prefetch-url “$url”)

But I get

error: attribute 'url' in selection path ‘FooBar.src.url' not found

Packages may have multiple url(s) so the attribute is urls

nix eval -f “<nixpkgs>” FooBar.src.urls

1 Like

Note that the nix eval function is not stable yet, and it seems that the flake version of nix eval breaks some common patterns. For now, the stable way of evaluating stuff is to use nix-instantiate (let me know if somebody knows how to condensate the with import ... stuff):

$ nix-instantiate --eval -E '1+1'
$ nix-instantiate --eval -E 'with import <nixpkgs> { }; vscode.version'

You can get a little bit shorter:

$ nix-instantiate --eval -E '(import <nixpkgs> {}).vscode.version'

But I would probably wrap it in a shell function to get rid of all the boilerplate:

$ nix-eval() { nix-instantiate --eval -E "with import <nixpkgs> {}; $*"; }
$ nix-eval vscode.version

Good to know, thanks. But any idea if it’s possible to remove the quotes "...", for example in this command? I’m looking for an equivalent of --raw in nix eval I guess.

$ nix-instantiate --eval -E 'builtins.fetchTarball {url = https://github.com/NixOS/nixpkgs/archive/925ae0dee63.tar.gz; sha256 = "1g3kkwyma23lkszdvgb4dn91g35b082k55ys8azc7j4s6vxpzmaw"; }'

# I would prefer:

I don’t think there is one built-in, but you could pipe the output to jq -r:

$ echo '"asdf"'
$ echo '"asdf"' | jq -r
1 Like

Also nix eval has a --raw option. See eg nixpkgs-upkeep/create-pr.sh at 7760afe4c5f699a5a621f77296df00d70173e4b4 · samuela/nixpkgs-upkeep · GitHub.

1 Like

@cole-h: ok thanks, I’ll do that then.

@samuela: you mean nix eval? If yes, the problem of nix eval is that it is not stable, and has different syntax between the flake version and the non flake one… which is quite annoying in scripts that need to be executed from both nix versions.

1 Like