Skip to main content

Writing Scripts in Nix

Create executible shell script

writeShellScriptBin

# custom-script.nix
{ pkgs, config, ...}:

let
  custom_script = pkgs.writeShellScriptBin "script_name" ''
    function() {
        if [ -n "$1" ] ; then
          echo $1
        fi    
    }
  '';

in {
  home = {
    packages = with pkgs;
      [
        custom_script
        other_packages
      ];
  };
}

which script_name outputs /home/dave/.nix-profile/bin/pwgen from your $PATH

programs.bash.shellInit

Alternatively with NixOS or HomeManager programs.bash.shellInit as follows placing it in .bashrc:

## custom-script.nix

    programs = {
      bash = {
        initExtra = ''
          function() {
            if [ -n "$1" ] ; then
              echo $1
            fi    
          }
        '';
      };
     };

Parameter Expansion

When porting bash scripts into nix files either and wanting to use bash expansion eg ${variable:0:1} make sure you escape the characters, otherwise it will be read literally upon rebuild and fail.

Don't do this:

  variable=value
  echo ${value^^}

error: syntax error, unexpected invalid token, expecting '}'

Do this instead:

  variable=value
  echo ''${value^^}