RubberDuckRubberDuck

Nix Cheat Sheet

6 months ago

Nix Package Manager

Basic Commands

Installation and Setup

  • Install Nix: curl -L https://nixos.org/nix/install | sh
  • Enter a Nix shell: nix-shell

Querying Packages

  • Search for a package: nix-env -qaP 'name'
  • Show installed packages: nix-env -q

Installing and Managing Packages

  • Install a package: nix-env -i pkg-name
  • Upgrade a package: nix-env -u pkg-name
  • Remove a package: nix-env -e pkg-name
  • Upgrade all installed packages: nix-env -u

Garbage Collection

  • Remove old package versions: nix-collect-garbage
  • Optimize the store (reduce disk usage): nix-store --optimise

Advanced Commands

Building from a Nix Expression

  • Build a Nix expression: nix-build default.nix

Creating Nix Shell Environments

  • Enter a development environment for a package: nix-shell -p pkg-name
  • Enter a shell with multiple packages: nix-shell -p pkg1 pkg2

Configuration

  • Edit user’s Nix configuration: nano ~/.nixpkgs/config.nix

Channels

  • List available channels: nix-channel --list
  • Add a new channel: nix-channel --add https://nixos.org/channels/nixpkgs-unstable
  • Update channels: nix-channel --update

Nix Programming Language

Basic Syntax and Concepts

Values

  • Integer: 42
  • String: "hello"
  • Multi-line String: ''Hello World''
  • Path: <nixpkgs>
  • URL: http://example.com

Lists and Sets

  • List: [ "value1" "value2" ]
  • Set: { key = "value"; key2 = "value2"; }
  • Access set attribute: set.key

Functions

  • Simple function: x: x + 1
  • Function with named arguments: { x, y }: x + y

Imports and Modules

  • Import a Nix file: import ./path/to/file.nix
  • Using a module in NixOS: imports = [ ./module.nix ];

Conditional and Operators

  • Equality: x == y
  • Inequality: x != y
  • Logical AND: x && y
  • Logical OR: x || y
  • Conditional: if condition then trueValue else falseValue

Built-in Functions

Lists

  • map: Apply a function to each element of a list
  • filter: Filter elements of a list
  • head: Get the first element of a list

Strings

  • concatStringsSep sep list: Concatenate a list of strings with a separator

Sets

  • attrNames set: Get list of attribute names in a set
  • attrValues set: Get list of attribute values in a set

General

  • builtins.length value: Get the length of a list or string
  • builtins.getEnv "HOME": Get environment variable

Derivations

  • Create a derivation: derivation { system = "x86_64-linux"; builder = ...; }

Inheritance

  • Inherit attributes from another set: { inherit (otherSet) key1 key2; }

Tips and Tricks

  1. Interpolation: You can interpolate Nix expressions in strings: "Hello ${name}!"
  2. Overlays: Useful for customizing packages or adding new ones in Nixpkgs.
  3. with statement: Import attributes from a set into scope, but use sparingly for clarity: with set; expression

Further Reading