zet.oliverdavies.uk/source/_notes/3.md

49 lines
1.2 KiB
Markdown

---
title: Writing bash scripts with Nix
date: 2024-08-21 18:30:24
tags: [Bash, Linux, Nix]
---
- Variables, such as username, can be injected.
- `shellcheck` is run automatically with `pkgs.writeShellApplication`.
- Packages defined in `runtimeInputs` will be automatically injected.
<https://github.com/opdavies/dotfiles.nix/blob/a1c356a1f576f041301a5c41d6ba7d0f098d0edb/lib/shared/scripts/export-video-list.nix>
```nix
{ pkgs, username, ... }:
{
name = "export-video-list";
runtimeInputs = with pkgs; [
jq
tree
udisks
];
text = ''
device_name="/dev/sda2"
device_label="UNTITLED"
source_path="/run/media/${username}/$device_label"
# If the source path doesn't exist, try mounting the device.
if [[ ! -d "$source_path" ]]; then
${pkgs.udisks}/bin/udisksctl mount -b "$device_name"
fi
# Exit early if the source path still doesn't exist.
if [[ ! -d "$source_path" ]]; then
echo "Error: $source_path not found."
exit 1
fi
output_file="$HOME/Documents/videos.json"
${pkgs.tree}/bin/tree -J "$source_path/Videos" | ${pkgs.jq}/bin/jq . > "$output_file"
${pkgs.jq}/bin/jq . < "$output_file"
'';
}
```