Nix is a powerful package manager that provides reproducible builds, isolated environments, and efficient package management. In this guide, we’ll explore how to use Nix for package management and environment setups.

1. Installing Software Packages with Nix

To install software packages, Nix uses the nix-env command. You can install a package with the following command:

1
nix-env -i <package-name>

For example, to install the hello package, use:

1
nix-env -i hello

2. Searching for Packages

You can search for available packages in the Nix package repository using the following command:

1
nix-env -qaP <package-name>

For example, to search for packages related to hello:

1
nix-env -qaP hello

This will list all available packages matching the name hello.

3. Listing Installed Packages

To see the list of installed packages, use the following command:

1
nix-env -q

This will display all the currently installed packages on your system.

4. Upgrading Installed Packages

To upgrade all installed packages to their latest versions, run:

1
nix-env -u

If you want to upgrade a specific package, for example, hello, you can use:

1
nix-env -u hello

5. Removing Packages

If you no longer need a particular package, you can uninstall it using the nix-env command:

1
nix-env -e <package-name>

For example, to uninstall hello, use:

1
nix-env -e hello

6. Using nix-shell for Isolated Environments

Nix provides nix-shell, which allows you to enter an isolated environment with specific dependencies. You can create a shell.nix file to define the environment for a project. Here’s an example of a shell.nix file:

1
2
3
4
5
6
7
# shell.nix
with import <nixpkgs> {};

stdenv.mkDerivation {
name = "hello-env";
buildInputs = [ hello ];
}

Once the shell.nix file is defined, enter the environment by running:

1
nix-shell

This will create a shell environment where the hello package and its dependencies are available.

7. Nix Configuration Files

In Nix, you can use configuration files to manage dependencies and software installation. Here’s an example of how to define a configuration in a Nix file. You can create a configuration file (e.g., default.nix) that specifies the packages to be installed:

1
2
3
4
5
6
7
# default.nix
with import <nixpkgs> {};

stdenv.mkDerivation {
name = "my-environment";
buildInputs = [ vim hello ];
}

Commenting in Nix Configuration Files

Nix allows you to add comments to your configuration files for clarity. Use # to add a comment:

1
2
3
4
5
6
7
# This is a simple Nix configuration file
with import <nixpkgs> {};

stdenv.mkDerivation {
name = "my-environment";
buildInputs = [ vim hello ]; # Install vim and hello package
}

In this example: