Nix-shell shebang: Difference between revisions
imported>Milahu add links: Speeding up nix-shell shebang, cached-nix-shell |
imported>Milahu add section: Performance |
||
Line 67: | Line 67: | ||
echo hello world | echo hello world | ||
</syntaxHighlight> | </syntaxHighlight> | ||
== Performance == | |||
TODO ... why the startup delay? how to make it faster? | |||
* [https://discourse.nixos.org/t/speeding-up-nix-shell-shebang/4048 Speeding up nix-shell shebang] | |||
* [https://github.com/xzfc/cached-nix-shell cached-nix-shell] - Instant startup time for nix-shell | |||
== See also == | == See also == | ||
Line 74: | Line 81: | ||
* [https://gist.github.com/travisbhartwell/f972aab227306edfcfea nix-shell and Shebang Lines] | * [https://gist.github.com/travisbhartwell/f972aab227306edfcfea nix-shell and Shebang Lines] | ||
* [https://notes.yukiisbo.red/posts/2021/07/Spice_up_with_Nix_Scripts.html Spice up with Nix: Scripts with magical dependencies] | * [https://notes.yukiisbo.red/posts/2021/07/Spice_up_with_Nix_Scripts.html Spice up with Nix: Scripts with magical dependencies] | ||
Revision as of 19:28, 2 April 2022
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
Performance
TODO ... why the startup delay? how to make it faster?
- Speeding up nix-shell shebang
- cached-nix-shell - Instant startup time for nix-shell