Skip to Content
OSLinux简单使用 nix 的包管理器

简单使用 nix 的包管理器

前言: 在 Linux 上使用 root 安装和使用 homebrew 有一些麻烦,虽然是为了安全考虑,但是我只是单纯想要一个快捷安装包的工具,然后我看到了 nix。

nix 有许多种安装包的方式。现在更推荐使用 nix profile 管理用户级别的常驻工具,命令更清晰,也更适合和 nix runnix shell 这类新命令一起使用。

还有其他的使用方式,比如使用 nix-shell 来临时修改你的 $PATH 环境变量。在决定永久安装某个软件之前,可以用它来试用该软件。

nix-env 属于传统方式,会永久修改已安装包的本地配置文件。它必须由用户以与传统包管理器相同的方式进行更新和维护,就和 apt 类似。

安装 nix 

# Multi-user installation (recommended) sh <(curl -L https://nixos.org/nix/install) --daemon

更新 nix channel

# 更新 channel 索引 nix-channel --update

使用 nix profile 

nix profile 适合安装常用命令行工具到当前用户环境:

# 安装包 nix profile add nixpkgs#<package-name> # 查询包 nix search nixpkgs "<package-name>" # 卸载包,可以使用 nix profile list 里的序号或包标识 nix profile remove <package-name-or-index> # 查看已安装的包 nix profile list # 更新 profile 里的所有包 nix profile upgrade --all # 清理旧 generation 和未使用的 store path nix-collect-garbage -d

也可以临时运行或进入带有某个包的 shell:

# 临时运行包 nix run nixpkgs#<package-name> # 临时进入带有包的环境 nix shell nixpkgs#<package-name>

如果提示需要开启 experimental feature,可以在命令后补充:

--extra-experimental-features "nix-command flakes"

常用 shell functions,可以放到 ~/.bashrc~/.zshrc 或其他 shell 配置中:

nxi() { nix profile add "nixpkgs#$1"; } nxs() { nix search nixpkgs "$1"; } nxr() { nix profile remove "$1"; } nxl() { nix profile list; } nxu() { nix profile upgrade --all; } nxgc() { nix-collect-garbage -d; } nxrun() { nix run "nixpkgs#$1"; } nxsh() { nix shell "nixpkgs#$1"; }

使用示例:

nxs ripgrep nxi ripgrep nxrun hello nxsh nodejs nxl nxu nxgc

传统方式:使用 nix-env 

一般情况下的bin路径:

/nix/var/nix/profiles/default/bin

包查询:https://search.nixos.org/packages?query= 

一般的安装:

# nix-env {--install | -i} args… [{--prebuilt-only | -b}] [{--attr | -A}] [--from-expression] [-E] [--from-profile path] [--preserve-installed | -P] [--remove-all | -r] nix-env -iA nixpkgs.<package-name>

卸载包:

# nix-env {--uninstall | -e} drvnames… nix-env -e <package-name>

查看已安装的包:

# nix-env {--query | -q} names… [--installed | --available | -a] [{--status | -s}] [{--attr-path | -P}] [--no-name] [{--compare-versions | -c}] [--system] [--drv-path] [--out-path] [--description] [--meta] [--xml] [--json] [{--prebuilt-only | -b}] [{--attr | -A} attribute-path] nix-env -q --installed

更新包:

# nix-env {--upgrade | -u} args [--lt | --leq | --eq | --always] [{--prebuilt-only | -b}] [{--attr | -A}] [--from-expression] [-E] [--from-profile path] [--preserve-installed | -P] nix-env -u <package-name>
Last updated on