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 提供了一套用于构建、安装和管理软件包的 tools

已验证的使用情况

nix-build

nix-build 构建 Nix 衍生版本,并将输出存储在 Nix 存储库中。它是构建可复现软件的首选方法。

# Step 1: Create a clean workspace
rm -rf /tmp/nix-hello-c && mkdir -p /tmp/nix-hello-c && cd /tmp/nix-hello-c

# Step 2: Write a C program
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 用于安装或删除用户配置文件中的各个软件包。

# Install the `hello` package
nix-env -iA nixos.hello

# Remove the `hello` package
nix-env -e hello
nix-shell

nix-shell 会创建一个包含指定依赖项的临时开发环境。这对于在不修改系统环境的情况下测试软件非常有用。

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

NixOS System Management

nixos-rebuild

nixos-rebuild 以声明式的方式管理整个系统配置。它会应用 configuration.nix 中定义的更改,是系统级软件包安装的推荐方法。

已验证的使用情况

# Edit the system configuration file
vim /etc/nixos/configuration.nix

# 应用配置更改并重建系统而无需重新引导
nixos-rebuild test