Nix-shell shebang
You can use nix-shell
as a script interpreter to
- run scripts in arbitrary languages
- provide dependencies with Nix
To do this, start the script with multiple shebang (#!
) lines.
The first shebang line is always #! /usr/bin/env nix-shell
.
The second shebang line declares the script language and the script dependencies.
Examples
Bash
To run bash scripts, set the interpreter with -i bash
#! /usr/bin/env nix-shell
#! nix-shell -i bash
echo hello world
You can use nix-shell -p ...
to add dependencies:
#! /usr/bin/env nix-shell
#! nix-shell -i bash -p imagemagick cowsay
# scale image by 50%
convert "$1" -scale 50% "$1.s50.jpg" &&
cowsay "done $1.q50.jpg"
Python
#! /usr/bin/env nix-shell
#! nix-shell -i python3
print("hello world")
#! /usr/bin/env nix-shell
#! nix-shell -i python3 -p python3Packages.pillow python3Packages.ansicolor
# scale image by 50%
import sys, PIL.Image, ansicolor
path = sys.argv[1]
image = PIL.Image.open(path)
factor = 0.5
image = image.resize((round(image.width * factor), round(image.height * factor)))
path = path + ".s50.jpg"
image.save(path)
print(ansicolor.green(f"done {path}"))
Pinning nixpkgs
To pin nixpkgs to a specific version, add a third shebang line:
#! /usr/bin/env nix-shell
#! nix-shell -i bash
#! nix-shell -I nixpkgs=https://github.com/NixOS/nixpkgs-channels/archive/nixos-18.03.tar.gz
echo hello world
See also
- nix-shell: Use As a #!-Interpreter in nix manual
- nix-shell: Use As a #!-Interpreter man page
- nix-shell and Shebang Lines
- Spice up with Nix: Scripts with magical dependencies
- Speeding up nix-shell shebang
- cached-nix-shell - Instant startup time for nix-shell