CheatSheet
日本語 icon日本語English iconEnglish
チートシートとはカンニングペーパーのことです。それが転じて、本来覚えることをまとめておいたものです。
要点をすぐに参照できるようにまとめてみました。

Nix

エンジニアのためのWebチートシート

Nixは、再現可能なビルドと宣言的なパッケージ管理を実現するツールです。 Nixパッケージマネージャー、Nix言語、Flakes、開発環境構築など、Nixエコシステム全体をチートシートにまとめました。

インストールと設定

インストール

  • マルチユーザーインストール(推奨)

    # Linux / macOS (multi-user, recommended)
    sh <(curl -L https://nixos.org/nix/install) --daemon
    
  • シングルユーザーインストール

    # Single-user (no daemon)
    sh <(curl -L https://nixos.org/nix/install) --no-daemon
    
  • アンインストール

    # macOS
    /nix/nix-installer uninstall
    

nix.conf 設定

  • ~/.config/nix/nix.conf または /etc/nix/nix.conf に設定を記述します。

    # ~/.config/nix/nix.conf
    experimental-features = nix-command flakes
    
    # Optional settings
    max-jobs = auto
    sandbox = true
    trusted-users = root @wheel
    substituters = https://cache.nixos.org
    auto-optimise-store = true
    keep-outputs = true
    keep-derivations = true
    

チャンネル管理

コマンド説明
nix-channel --add https://nixos.org/channels/nixpkgs-unstable安定版チャンネルを追加します。
nix-channel --updateチャンネルを更新します。
nix-channel --list登録済みチャンネルを一覧表示します。
nix-channel --remove nixpkgsチャンネルを削除します。

新CLIコマンド(nix)

コア操作

コマンド説明
nix buildパッケージまたはFlakeをビルドします。
nix develop開発シェル環境に入ります。
nix run nixpkgs#helloパッケージのアプリケーションを直接実行します。
nix shell nixpkgs#nodejs nixpkgs#yarn一時的にパッケージが利用可能なシェルを起動します。
nix search nixpkgs pythonパッケージを名前や説明で検索します。
nix eval nixpkgs#hello.versionNix式を評価して結果を表示します。
nix repl対話的なNix REPLを起動します。
nix fmtNixコードをフォーマットします。
nix log nixpkgs#helloビルドログを表示します。
nix path-info nixpkgs#helloストアパスの情報を表示します。
nix copy --to ssh://server /nix/store/...ストアパスを別のストアにコピーします。
nix hash path ./my-projectファイルやディレクトリのハッシュを計算します。

プロファイル管理

コマンド説明
nix profile install nixpkgs#ripgrepパッケージをプロファイルにインストールします。
nix profile remove packages.nixpkgs.ripgrepパッケージをプロファイルから削除します。
nix profile listインストール済みパッケージを一覧表示します。
nix profile upgrade '.*'パッケージを最新版に更新します。
nix profile rollbackプロファイルを前の世代に戻します。

レガシーコマンド

nix-env(パッケージ管理)

コマンド説明
nix-env -iA nixpkgs.ripgrep属性パスを指定してインストールします。
nix-env -i ripgrepパッケージを名前でインストールします。
nix-env -qインストール済みパッケージを一覧表示します。
nix-env -qaP '.*python.*'利用可能なパッケージを検索します。
nix-env -e ripgrepパッケージをアンインストールします。
nix-env -u ripgrep特定のパッケージをアップグレードします。
nix-env -u全パッケージをアップグレードします。
nix-env --rollback前の世代にロールバックします。
nix-env --list-generations世代の一覧を表示します。
nix-env --switch-generation 42指定した世代に切り替えます。

nix-shell / nix-build / nix-store

コマンド説明
nix-shell開発シェルに入ります(shell.nixまたはdefault.nix)。
nix-shell -p nodejs yarn一時的にパッケージを利用できるシェルを起動します。
nix-shell --pureホスト環境の変数を除外したピュアシェルを起動します。
nix-builddefault.nixまたは指定したNix式をビルドします。
nix-build -A hello属性パスを指定してビルドします。
nix-instantiate --eval -E '1 + 2'Nix式を評価してストアパスを出力します。

Flakes

flake.nix の基本構造

  • Flakeの基本的なファイル構造です。

    {
      description = "My project flake";
    
      inputs = {
        nixpkgs.url = "github:NixOS/nixpkgs/nixos-24.11";
        flake-utils.url = "github:numtide/flake-utils";
      };
    
      outputs = { self, nixpkgs, flake-utils }:
        flake-utils.lib.eachDefaultSystem (system:
          let
            pkgs = nixpkgs.legacyPackages.${system};
          in {
            packages.default = pkgs.hello;
    
            devShells.default = pkgs.mkShell {
              buildInputs = [ pkgs.nodejs pkgs.yarn ];
            };
    
            apps.default = {
              type = "app";
              program = "${pkgs.hello}/bin/hello";
            };
          }
        );
    }

inputs の書き方例

  • Flakeの依存関係(inputs)の記述パターンです。

    inputs = {
      # GitHub repository (default branch)
      nixpkgs.url = "github:NixOS/nixpkgs/nixos-24.11";
    
      # GitHub repository (specific branch)
      nixpkgs-unstable.url = "github:NixOS/nixpkgs/nixos-unstable";
    
      # Follow another input's nixpkgs
      home-manager = {
        url = "github:nix-community/home-manager";
        inputs.nixpkgs.follows = "nixpkgs";
      };
    
      # Git repository
      my-repo.url = "git+https://example.com/repo.git";
    
      # Local path
      my-local.url = "path:./subdir";
    };

Flakeコマンド

コマンド説明
nix flake initカレントディレクトリにflake.nixテンプレートを生成します。
nix flake init -t templates#rustテンプレートを指定してFlakeを初期化します。
nix flake update全入力の依存関係を最新版に更新します。
nix flake lock --update-input nixpkgs特定の入力のみを更新します。
nix flake showFlakeが提供する出力を表示します。
nix flake checkFlakeの出力を検証します。
nix flake metadataFlakeのメタデータ(入力、リビジョン等)を表示します。

Nix言語基礎

データ型とリテラル

  • Nix言語の基本的な型とリテラルの書き方です。

    # String
    "hello world"
    ''
      multi-line
      string
    ''
    
    # Integer & Float
    42
    3.14
    
    # Boolean
    true
    false
    
    # Null
    null
    
    # Path (not a string!)
    /etc/nixos/configuration.nix
    ./flake.nix
    ~/.config/nix
    
    # List (space-separated, no commas)
    [ 1 2 3 "hello" true ]
    
    # Attribute Set (key-value pairs)
    { name = "nix"; version = "2.24"; }
    
    # Nested attribute set
    { a.b.c = 1; }
    # equivalent to: { a = { b = { c = 1; }; }; }
    
    # Attribute access
    let x = { a = 1; b = 2; }; in x.a  # => 1
    
    # Has attribute operator
    { a = 1; } ? a   # => true
    
    # Merge attribute sets
    { a = 1; } // { b = 2; }  # => { a = 1; b = 2; }
    
    # String interpolation
    let name = "world"; in "hello ${name}"
    

関数定義

  • Nix言語の関数(ラムダ式)の定義パターンです。

    # Single argument
    x: x + 1
    
    # Multiple arguments (curried)
    x: y: x + y
    
    # Apply function
    let add = x: y: x + y; in add 1 2  # => 3
    
    # Attribute set argument (destructuring)
    { name, age }: "I am ${name}"
    
    # With default values
    { name, age ? 25 }: "Age: ${toString age}"
    
    # With extra attributes allowed
    { name, ... }: name
    
    # Named attribute set argument
    args@{ name, age }: args
    
    # Equivalent
    { name, age } @ args: args
    
    # builtins (commonly used)
    builtins.map (x: x * 2) [ 1 2 3 ]  # => [ 2 4 6 ]
    builtins.filter (x: x > 2) [ 1 2 3 4 ]  # => [ 3 4 ]
    builtins.length [ 1 2 3 ]  # => 3
    builtins.attrNames { a = 1; b = 2; }  # => [ "a" "b" ]
    builtins.hasAttr "a" { a = 1; }  # => true
    builtins.toString 42  # => "42"
    builtins.toJSON { a = 1; }  # => "{\"a\":1}"
    builtins.readFile ./file.txt
    builtins.fetchurl "https://example.com"
    

キーワード・構文

キーワード説明
let ... inローカル変数を定義します。let x = 1; y = 2; in x + y
with属性セットのスコープを展開します。with pkgs; [ nodejs yarn ]
inherit外部スコープから属性を継承します。{ inherit name; } = { name = src.name; }
if / then / else条件分岐(全ての分岐が値を返す式)。if x > 0 then "pos" else "neg"
import別のNixファイルを読み込みます。import ./config.nix
rec再帰的属性セット(属性間で相互参照可能)。rec { x = 1; y = x + 1; }
assert条件を検証し、偽の場合はエラーにします。assert x > 0; x
or(デフォルト値)属性が存在しない場合のデフォルト値を指定します。attrs.name or "default"

開発環境

shell.nix(レガシー)

  • 従来のshell.nixを使った開発環境の定義です。

    # shell.nix
    { pkgs ? import <nixpkgs> {} }:
    
    pkgs.mkShell {
      buildInputs = with pkgs; [
        nodejs_22
        yarn
        python3
        postgresql
      ];
    
      shellHook = ''
        echo "Dev environment loaded!"
        export DATABASE_URL="postgresql://localhost/mydb"
      '';
    }

devShells(Flakes)

  • Flakeを使った開発環境の定義です。

    # flake.nix
    {
      inputs.nixpkgs.url = "github:NixOS/nixpkgs/nixos-24.11";
      inputs.flake-utils.url = "github:numtide/flake-utils";
    
      outputs = { nixpkgs, flake-utils, ... }:
        flake-utils.lib.eachDefaultSystem (system:
          let pkgs = nixpkgs.legacyPackages.${system};
          in {
            devShells.default = pkgs.mkShell {
              buildInputs = with pkgs; [
                nodejs_22
                yarn
                python3
              ];
              shellHook = ''
                echo "Dev environment loaded!"
              '';
            };
          }
        );
    }

direnv 連携

  • direnvを使ってディレクトリに入ると自動で環境をロードします。

    # Install direnv & nix-direnv
    nix profile install nixpkgs#direnv nixpkgs#nix-direnv
    
    # .envrc (for Flakes)
    use flake
    
    # .envrc (for shell.nix)
    use nix
    
    # Allow direnv for the directory
    direnv allow
    

Nixストア & ガベージコレクション

Nixストアの構造

  • Nixの全パッケージは/nix/store配下にハッシュ付きパスで格納されます。

    /nix/store/<hash>-<name>-<version>
    
    # Example
    /nix/store/w2dlk3n5p6ak...-nodejs-22.12.0
    /nix/store/a9z4q3m8j2bx...-hello-2.12.1
    
    # Key characteristics:
    # - Immutable (read-only)
    # - Content-addressed (hash of all inputs)
    # - Shared across users
    # - Dependencies are explicit

ガベージコレクション & ストア管理

コマンド説明
nix-collect-garbage不要なストアパスを削除します。
nix-collect-garbage -d古い世代を全て削除してからGCを実行します。
nix store gcNixストアのガベージコレクションを実行します。
nix store optimise重複ファイルをハードリンクでまとめてディスク使用量を削減します。
nix-store -q --references /nix/store/...指定したストアパスの依存関係を表示します。
nix-store -q --tree /nix/store/...依存関係をツリー形式で表示します。
nix store delete /nix/store/...指定したストアパスを削除します。

エコシステム

主要ツール・プロジェクト

ツール説明
Nixpkgs100,000以上のパッケージを含むNix公式パッケージリポジトリ。
NixOSNixパッケージマネージャーを基盤とした宣言的Linux ディストリビューション。
Home Managerホームディレクトリの設定(dotfiles等)をNixで宣言的に管理するツール。
nix-direnvdirenvとNixの統合。開発環境の自動ロードとGCルート登録を行います。
devenvCachix提供の開発環境フレームワーク。簡潔な設定で再現可能な環境を構築します。
CachixNixバイナリキャッシュサービス。ビルド済みパッケージを共有・再利用できます。
nix-darwinmacOSのシステム設定をNixで宣言的に管理するツール(NixOSのmacOS版)。
flake-utilsFlakeのボイラープレートを削減するユーティリティライブラリ。