Skip to content

NixOS 常用命令

安装程序

  • 使用 nix-env 安装的包不会被自动记录到 Nix 的声明式配置中
  • New CLI 中对应命令为 nix profile
# 安装包
nix-env -iA nixpkgs.hello
# 移除包
nix-env -e nixpkgs.hello
# 搜索包
nix-env -qaP hello
  • nix-shell 一般用于临时使用某个包,退出 shell 后不会污染环境。
nix-shell -p hello
# 带 nix 语句的命令
nix-shell -p 'python38.withPackages (packages: [ packages.django ])'

处理 nix store

  • 使用 nix-store 手动处理 nix store。
  • 构建指定的 path,输入的 path 可以是 derivation
nix-store --realize path --add-root path
  • nix-instantiate
  • 通过有输出 derivation 的文件实例化为一个 drv 文件
nix-instantiate test.nix
# 之后通过 `nix-store` 进行构建
nix-store -r $(nix-instantiate test.nix)

垃圾回收

# 查询所有历史版本
nix profile history --profile /nix/var/nix/profiles/system
# 清理历史版本,不会删除数据
nix profile wipe-history --older-than 7d --profile /nix/var/nix/profiles/system

# `-d` 指示删除 `/nix/var/nix/profiles` 下所有的 old generations
nix-collect-garbage -d

更新配置

  • 使用镜像更新
home-manager switch --flake ".#$(hostname)" --impure --option substituters "https://mirrors.tuna.tsinghua.edu.cn/nix-channels/store"

nix flake check --option substituters "https://mirrors.tuna.tsinghua.edu.cn/nix-channels/store"

调试 Nix 表达式

  • 常用命令 :lf <ref>:e <expr>

# 进入解释器
nix repl

# 读取当前 flake 输出
:lf .
# 查看变量
<TAB>
# 查看 inputs 下的变量
inputs.<TAB>

# 加载 nixpkgs
nix repl -f '<nixpkgs>'
# 禁用 NIX_PATH 的情况
nix repl -f flake:nixpkgs

同步 flake 版本

使当前 flake 与系统版本同步

nix flake update --override-input nixpkgs "github:nixos/nixpkgs/$(nixos-version --revision)"

更新单个 input

nix flake update nixpkgs

其它命令

查看当前配置 nix show-config


查看 flake 的 drv

nix show-derivation .#nixosConfigurations.yoshika.config.system.build.toplevel

比较两个 closures

nix store diff-clousures path1 path2

evaluate outPath

nix eval nixpkgs#firefox.outPath

References

nix.dev
Haskell for all: How to correctly cache build-time dependencies using Nix