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
"1.48.2"

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'.

2 Likes

Answering my own question:

❯ nix eval -f '<nixpkgs>' 'vscode.version'
"1.48.2"
7 Likes

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

e.g.,

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'
2
$ nix-instantiate --eval -E 'with import <nixpkgs> { }; vscode.version'
"1.45.0"
3 Likes

You can get a little bit shorter:

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

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
"1.45.0"
3 Likes

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"; }'
"/nix/store/m59d3v89nhp9207hgvf6v21wxq7lhq64-source"

# I would prefer:
/nix/store/m59d3v89nhp9207hgvf6v21wxq7lhq64-source

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

$ echo '"asdf"'
"asdf"
$ echo '"asdf"' | jq -r
asdf
2 Likes

Also nix eval has a --raw option. See eg https://github.com/samuela/nixpkgs-upkeep/blob/7760afe4c5f699a5a621f77296df00d70173e4b4/create-pr.sh#L14.

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