Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Nix and NixOS Tools

This category covers Nix package management tools and NixOS system management tools.

軟體包管理

Nix

NixOS 提供了一套用於建置、安裝與管理軟體包的工具

Verified Usage

nix-build

nix-build builds Nix derivations and produces outputs in the Nix store. It is the preferred way to build software reproducibly.

# 第 1 步:建立乾淨的工作空間
rm -rf /tmp/nix-hello-c && mkdir -p /tmp/nix-hello-c && cd /tmp/nix-hello-c

# 第 2 步:編寫 C 程式
cat > hello.c <<'EOF'
#include <stdio.h>

int main(void) {
    puts("Hello, World!");
    return 0;
}
EOF

# Step 3: Write a default.nix
cat > default.nix <<'EOF'
{ pkgs ? import <nixpkgs> {} }:

pkgs.stdenv.mkDerivation {
  pname = "hello-c";
  version = "0.1.0";
  src = ./.;

  dontConfigure = true;

  buildPhase = ''
    cc hello.c -o hello
  '';

  installPhase = ''
    mkdir -p $out/bin
    install -m755 hello $out/bin/hello
  '';
}
EOF

# Step 4: Build and run
nix-build
./result/bin/hello
nix-env

nix-env 會安裝或移除您的使用者設定檔中的個別軟體包。

# 安裝 `hello` 軟體包
nix-env -iA nixos.hello

# 移除 `hello` 軟體包
nix-env -e hello
nix-shell

nix-shell creates a temporary development environment with the specified dependencies. This is useful for testing software without modifying your system environment.

# Enter a shell with the `hello` package available
nix-shell -p hello

NixOS System Management

nixos-rebuild

nixos-rebuild manages the entire system configuration declaratively. It applies changes defined in configuration.nix, and is the recommended approach for installing packages system-wide.

Verified Usage

# 編輯系統組態檔
vim /etc/nixos/configuration.nix

# Apply configuration changes and rebuild the system without rebooting
nixos-rebuild test