Skip to content

Instantly share code, notes, and snippets.

@abcdw
Created October 6, 2020 16:21
Show Gist options
  • Save abcdw/8b29ee06c05c43369e27de183a71449d to your computer and use it in GitHub Desktop.
Save abcdw/8b29ee06c05c43369e27de183a71449d to your computer and use it in GitHub Desktop.

Nix syntax basics

Intro

Comments

# line comments

/* multiline
   comments */

Types

Basic types

[
  true # b
  1 2 3.5
  "hello"
  { k = "v"; k2 = "v2"; } # unorder
  /tmp/file.nix ./file.nix
]

Lazy Reccursive AttrSet

rec { a = "12"; b = "something" + a; c."k1"."${b}" = "value"; }
rec { a = 12; b = { k = b; }; }.b.k

Strings

''
  multi line
   ${toString (10 + 15)}
  string
  with multiple lines''

Conditionals

if is expression

if 3 > 5 then "greater" else "less"

Functions

Simple

a: { t = "test";  b = a; }

Application

((a: a + 1) 2)

More complex

{a ? null, ...}@args: b: { result = args; }

Scope helpers

  • let
  • inherit
  • with
let
  a = { b = { c = "1"; d = 2; }; };
in
with a;
{ inherit (b); }

Imports

import ./test.nix {}

builtins && lib

https://github.com/NixOS/nixpkgs/tree/master/lib
let
  lib = (import <nixpkgs> {}).lib;
in
{ ea = builtins.elemAt; lb = lib.strings; }

loops

There is no loops, oops.

How to live without loops ideas:

  • map
  • filter
  • foldl

Impurities

#{ pkgs ? import <nixpkgs> {} }:
let
  pkgs = import <nixpkgs> {};
  newPkg = pkgs.writeText "hello.txt" "Hello world!";
  # and different fetchSomething functions
in
"${builtins.getEnv "HOME"} and ${newPkg}"

Modules

{ config, pkgs, ...}:
{
  options = {};
  config = {};
}

Home-manager module example.

Links

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment