Daniel Siepmann - Coding is Art

Blog Post

Organising shell scripts

Published: , Updated:

Topics: nix, unix

Introduction

I've a small collection of custom shell scripts for various tasks. Many people use different ways of organizing those scripts. I'm using nix home-manager to actually create those scripts. I'll explain the benefits of using home-manager as a wrapper. And I'll explain my naming convention and why I follow the convention.

Building shell scripts with nix home-manager

I'm using https://nix-community.github.io/home-manager/ to maintain my shell scripts. Each script is a package like Firefox or Neovim that is installed via home-manager. Nix allows to define Packages nicely, a custom shell script looks like this:

{
  writeShellApplication,
  git
}:

writeShellApplication {
  name = "custom-push-etckeeper";

  runtimeInputs = [
    git
  ];

  text = ''
    mkdir /tmp/etckeeper
    cd /tmp/etckeeper
    sudo cp -r /etc/.git .
    sudo chown -R daniels:daniels .
    git push
    cd /tmp
    rm -rf /tmp/etckeeper
  '';
}

The text variable holds the actual script which is converted to a “ShellApplication”. That's nix name for a shell script. Nix will use the expression and create the proper shell script for myself. It will add some stages, e.g. a test stage that will execute https://www.shellcheck.net/. That is a linter to prevent bugs within shell scripts.

Shell scripts are executable and nix creates a file with the name that is an executable and home-manager will place it within my PATH. Nix will also take care to properly import the dependencies, e.g. git.

That way I've created a shell script not worrying about the environment, like being git available, or making the file executable and not worrying too much about proper quoting, thanks to linting via Shellcheck.

Naming Convention

All my shell scripts start with custom-.That allows me to type cust followed by the tab key to start https://github.com/junegunn/fzf to fuzzy search all my custom shell scripts. I also have project specific shell scripts managed via nix shell.nix. Those start with project- allowing me to decide whether I want to search user or project specific scripts.

Acknowledgements

The following post motivated me to write this post: https://blog.cron.world/article_08.html by https://fosstodon.org/@Anachron.