Nix Tmux
A quick blog post on using nix with Tmux.
Tmux is one of my favourite tools. Recently I have been playing with Go Networking which often requires multiple terminals. Fortunately Tmux is great for this experience, but I often want to have a pre-defined setup.
Enter Nix and Tmux to manage the environment effortlessly.
You can amend the configuration used to setup the screen however you wish.
Just amend the dev.tmux script to realign your screen layout however you want.
Nix Scripts
We can define a script to represent the environment requirement.
-
Lets create a tmux layout script
dev.tmux:1# dev.tmux 2SESSION="go-dev" 3 4# Check if the session already exists 5tmux has-session -t $SESSION 2>/dev/null 6 7if [ $? != 0 ]; then 8 # Create session, split panes 9 tmux new-session -d -s $SESSION 10 tmux split-window -h -t $SESSION 11 tmux split-window -v -t $SESSION 12fi 13 14# Attach 15tmux attach-session -t $SESSIONIn the above
dev.tmuxscript we create a new session, then split the window both vertically and horizontally. -
We need to tell Nix to add the
dev.tmuxexternal script as a dependency.1let 2 # External Script: This reads './dev.tmux' and puts it into a binary named 'dev-tmux' 3 tmuxLayout = pkgs.writeShellScriptBin "dev-tmux" (builtins.readFile ./dev.tmux); 4inwriteShellScriptBinlets us definedev-tmuxwrapping the local scriptdev.tmux -
Now we can create a
shell.nixscript:1with import <nixpkgs> {}; 2 3let 4 # External Script: This reads './dev.tmux' and puts it into a binary named 'dev-tmux' 5 tmuxLayout = pkgs.writeShellScriptBin "dev-tmux" (builtins.readFile ./dev.tmux); 6in 7pkgs.mkShell { 8 9 name = "go-dev"; 10 nativeBuildInputs = with pkgs; [ 11 go 12 tmux 13 tmuxLayout # Custom script with Tmux layout 14 ]; 15 16 LANGUAGE = "Go"; 17 VERSION = "go version"; 18 19 shellHook = '' 20 # Optional: Script environment start up 21 echo "Welcome to $LANGUAGE Development Environment" 22 $VERSION 23 24 # The Trap: This kills the tmux session as soon as you exit the nix-shell 25 # It ensures no "ghost" sessions stay running in the background. 26 trap "tmux kill-session -t go-dev" EXIT 27 28 # Perform Tmux Dev Layout 29 dev-tmux 30 ''; 31}The above script will still give us a
tmuxenvironment. When the nix script executes it will automatically call the dev-tmux to handle the screen layout. In addition there is atrapdefined to kill existing sessions on exit. -
Run the script:
1nix-shell --pureRemember a pure environment tries to ignore the existing host configuration 😂 Nix will automatically look for the file
shell.nixso you dont need to added this parameter 🥰Expected Output:
1Welcome to Go Development Environment 2go version go1.25.5 darwin/arm64Awesome, Tmux is configured and ready to go!
-
Exit the Nix Shell
To exit, you will need to exit each screen individually.
1exit
Nice we now have a super easy way to run Tmux on a Nix machine.