Nix-shell Shebang + Flakes + Haskell

I like running Haskell like scripts, e.g.

#!/usr/bin/env nix-shell
#!nix-shell --pure -i runghc ./default.nix

{-# LANGUAGE OverloadedRecordDot #-}
{-# LANGUAGE DuplicateRecordFields #-}

import Data.Random.Normal (normal')
...

However, sometimes I’d like to use flakes also.

GPT suggests creating a bash script which calls nix develop -c runghc .. - not what I’m looking for…

Could you give a little more explanation of what you’re hoping to do?

My understanding of what you’re saying is that you want to write a flake.nix, so that instead of writing the shebang line in your Haskell script like:

#!/usr/bin/env nix-shell
#!nix-shell --pure -i runghc ./default.nix

you’d instead write something like:

#!/usr/bin/env some-nix-flake-command
#(...some sort of flake-specific options that use your ./flake.nix file...)

Off the top of my head I don’t know how you’d do this, but unless you absolutely don’t want to use nix-shell, it might be possible to write a short nix-shell script that uses something like builtins.getFlake to load a flake from the nix-shell command line?

1 Like

The documentation suggests that it should be possible nix - Nix Reference Manual

They mention this example:

#!/usr/bin/env nix
#! nix shell nixpkgs#bash nixpkgs#hello nixpkgs#cowsay --command bash

hello | cowsay

So I would expect:

#!/usr/bin/env nix
#! nix shell nixpkgs#ghc --command runghc

main = putStrLn "Hello"

(after chmod +x) to work… but surprisingly even the code from the documentation fails for me with error: './test.hs' is not a recognised command. If someone knows what I did wrong?

2 Likes

Oh, actually, I managed to get it work with:

#!/usr/bin/env -S nix shell nixpkgs#bash nixpkgs#hello nixpkgs#cowsay --command bash

hello | cowsay

and for the ghc version:

#!/usr/bin/env -S nix shell nixpkgs#ghc --command runghc

main = putStrLn "Hello"

Edit: no idea why I can’t get the multiline version working for nix, reported here nix: Multiline shebang not working · Issue #280033 · NixOS/nixpkgs · GitHub

3 Likes