Nix 包管理器与表达式语言

精选 Nix 常用指令与核心速查备忘单,涵盖高频用法、配置参数与实用技巧。 本备忘单旨在为编写基础 Nix 声明式配置文件与表达式代码提供快速检索参考。

#数据类型与语法 (Types & Syntax)

#字符串 (String)

let
  x = "single-line string";
  y = ''
    multi-line string
  '';
in

#整数 (Integer)

let
  x = -123;
  y - 123;
in

#浮点数 (Float)

let
  x = -0.32;
  y = 0.45;
in

#布尔值 (Boolean)

let
  x = true;
  y = false;
in

#空值 (Null)

let
  x = null;
in

#路径 (Path)

let
  x = /absolute/path;
  y = ./relative/path;
in

#属性集 (Attribute Set)

let
  x = {
    a = 1;
    b = 2;
  };
  y = { c = 3; };
in

参见 属性集 (Attribute Sets)

#列表 (List)

let
  x = [ 1 2.0 ];
  y = [
    1
    "this is a string"
    23.0
    null
  ];
in

#注释 (Comment)

↓ 单行注释 (Single-line comment)

# your comment

↓ 多行注释 (Multi-line comment)

/*
  your comment
*/

#作用域控制 (Scoping)

#定义局部变量 (Define Local Variable)

let
  x = 1;
  y = 2;
in
  x + y # -> 返回 3

#变量引入作用域 (Add Variables Into Scope)

let
  x = 1;
in
  { inherit x; }

↓ 解糖语法等价于 (Desugars to)

let
  x = 1;
in
  { x = x; }

#属性引入作用域 (Add Attributes Into Scope)

let
  x = { y = 1; };
in
  { inherit (x) y; }

↓ 解糖语法等价于 (Desugars to)

let
  x = { y = 1; };
in
  { y = x.y; }

#所有属性全量引入 (Add All Attributes Into Scope)

let
  x = { y = 1; z = 2;  };
in
  with x;
  y + z # -> 返回 3

#条件判断 (Conditionals)

#条件表达式定义 (Define Conditionals)

if x > 0
then 1
else -1

#属性集操作 (Attribute Sets)

#定义属性集 (Define Attribute Sets)

let
  x = {
    a = 1;
    b = 2;
  };
  y = { c = 3; };
in

#更新合并属性集 (Update Attribute Sets)

{ x = 1; } // { y = 2; } # -> 返回 { x = 1; y = 2; }
{ x = 1; } // { x = 2; } # -> 返回 { x = 2; }

#检查属性是否存在 (Check For Attribute)

let
  x = { y = 1; };
in
  x ? y # -> 返回 true

#引用属性键值 (Reference Attribute Keys)

let
  x = { y = 1; };
in
  x.y # -> 返回 1

↓ 可选默认值 (可选 fallback)

let
  x = { y = 1; };
in
  x.z or 2 # -> 返回 2

#拼接与插值 (Concatenation & Interpolation)

#拼接列表 (Concatenate Lists)

[ 1 2 ] ++ [ 3 4 ] # -> 返回 [ 1 2 3 4 ]

#拼接路径与字符串 (Concatenate Paths & Strings)

/bin + /sh # -> 返回 /bin/sh
/bin + "/sh" # -> 返回 /bin/sh
"/bin" + "/sh" # -> 返回 "/bin/sh"

#字符串内嵌插值 (Interpolate Strings)

let
  x = "bar";
in
  "foo ${x} baz" # -> 返回 "foo bar baz"

#函数定义 (Functions)

#基础单参函数 (Simple Function)

let
  f = x: x + 1;
in
  f 1 # -> 返回 2

#柯里化多参数函数 (Multiple Arguments)

let
  f = x: y: [ x  y ];
in
  f 1 2 # -> 返回 [ 1 2 ]

#解构命名参数 (Named Arguments)

let
  f = {x, y}: x + y;
in
  f { x=1; y=2; } # -> 返回 3

↓ 忽略额外参数 (Ignoring arguments)

let
  f = {x, y, ... }: x + y;
in
  f { x=1; y=2; z=3; } # -> 返回 3

↓ 参数默认值 (默认值s)

let
  f = {x, y ? 2 }: x + y;
in
  f { x=1; } # -> 返回 3

↓ 绑定整体对象变量 (Bind to variable)

let
  f = {x, y}@args: args.x + args.y;
in
  f { x=1; y=2; } # -> 返回 3

#🔗 参考资源 (Sources)