Bundling Scripts with Nix
I write a lot of shell scripts.
Many are one-offs or specific to a project,
but every so often,
I’ll have a script that transcends to become a part of my toolbelt.
For example, nix-op-key
is a script I wrote to generate new Nix signing keys
and place them in 1Password.
It’s not a task that requires a dedicated program,
it just needs to glue two existing programs together:
nix key generate-secret
and op
(the 1Password CLI).
These sorts of scripts are great,
but if you want to share them with someone else
(or even just use it on a different computer),
how do you do it?
Scripts like these depend on specific programs (or maybe even specific versions) being installed
and Bash does not have a package manager like pip
or the go
tool.
As it turns out, Nix is such a package manager.
And with flakes, there’s built-in support for installing and running scripts
with well-specified dependencies
in a single command.
For example, you can run my nix-op-key
script I mentioned earlier
(pinned to a specific version)
with:
COMMIT=25e9bd52e977cca415df84ea91028efd92d3da92
nix run "github:zombiezen/dotfiles?dir=nix&rev=$COMMIT#nix-op-key" -- --help
Furthermore, you can install the script using the nix profile install
command:
nix profile install "github:zombiezen/dotfiles?dir=nix&rev=$COMMIT#nix-op-key"
(If you try this out yourself, you can uninstall the script with
nix profile remove '.*.nix-op-key'
).
In this blog post, I’ll show you how you can package your own shell scripts with Nix to make them more reliable and easier to share. This article assumes familiarity with Unix command line and Bash shell scripting. I’m using Nix 2.17.1. All of the source code in this post is released under the Unlicense and is available on GitHub.