安装Nix
sh <(curl -L https://mirrors.tuna.tsinghua.edu.cn/nix/latest/install) --daemon
根据脚本指示完成安装,中间可能需要输入几次Y来授权执行相关sudo命令。视网络环境不同,执行nix-channel --update nixpkgs命令时可能卡顿一小会儿。
基于ArchLinux安装Nix也可以使用:
sudo pacman -S nix,但该方式有诸多问题,比如:没有自动创建/nix/store目录,build时/nix/var/nix/builds/目录没有权限等等。
配置Nix基础环境
sudo tee -a /etc/nix/nix.conf << EOF
# 启用 nix-command 和 flakes 的实验性功能
experimental-features = nix-command flakes
# 设置镜像源
substituters = https://mirrors.tuna.tsinghua.edu.cn/nix-channels/store https://mirrors.ustc.edu.cn/nix-channels/store https://cache.nixos.org/
EOF
sudo systemctl restart nix-daemon
在用户配置~/.config/nix/nix.conf中设置
substituters,需要在全局配置/etc/nix/nix.conf中增加trusted-users配置才能生效,为了避免配置分散,直接使用全局配置。
初始化Home Manager与Flakes
nix run home-manager/master -- init --switch
home-manager --version
参见官方Home Manager Manual页面。
执行上述命令后,会自动在~/.config/home-manager目录下生成home.nix和flake.nix(flake.lock)配置文件。
配置Home Manager
修改home.nix配置:
cd ~/.config/home-manager
mv home.nix home.nix.bak
cat > home.nix << 'EOF'
{ config, pkgs, ... }:
{
home.username = "luanrz";
home.homeDirectory = "/home/luanrz";
home.stateVersion = "26.05";
home.packages = with pkgs; [
hello
vim
];
home.file = {
};
home.sessionVariables = {
};
programs.home-manager.enable = true;
}
EOF
更新home-manager:
home-manager switch
如果新旧配置文件出现冲突,可以使用
-b backup参数自动备份原文件:home-manager switch -b backup
配置Flakes
更新home-manager时不会自动更新flake,如果修改了~/.config/home-manager下的flake.nix配置,可执行下述命令更新flake:
cd ~/.config/home-manager
nix flake update
卸载Nix
参见官方Uninstalling Nix页面。
# Remove the Nix daemon service
sudo systemctl stop nix-daemon.service
sudo systemctl disable nix-daemon.socket nix-daemon.service
sudo systemctl daemon-reload
# Remove files created by Nix
sudo rm -rf /etc/nix /etc/profile.d/nix.sh /etc/tmpfiles.d/nix-daemon.conf /nix ~/.local/share/nix ~/.local/state/nix ~/.cache/nix ~/.nix-defexpr ~/.nix-profile ~/.nix-channels ~root/.nix-channels ~root/.nix-defexpr ~root/.nix-profile ~root/.cache/nix
# Remove build users and their group
for i in $(seq 1 32); do
sudo userdel nixbld$i
done
sudo groupdel nixbld
# (Optional) Remove other files created by Nix and restore the original one
sudo mv /etc/bash.bashrc.backup-before-nix /etc/bash.bashrc
sudo mv /etc/bashrc.backup-before-nix /etc/bashrc
sudo mv /etc/profile.backup-before-nix /etc/profile
sudo mv /etc/zsh/zshrc.backup-before-nix /etc/zsh/zshrc
sudo mv /etc/zshrc.backup-before-nix /etc/zshrc