Bash functions, home-manager

I have this simple bash function

cdl () {
    cd "$(dirname "$(readlink "$1")")"; 
}

In home-manager, where’s the best place to add this? I use shellaliases for aliases, but is there something like a shellfunctions?

I think you are searching for a classical dotfile manager.

There is no general interface for functions in home-manager.

The fish module does provide a nix-agnostic way to define functions but for zsh I just put them in initExtra

Yeah, I would suggest simply doing

programs.bash.initExtra = ''
  cdl () {
    cd "$(dirname "$(readlink "$1")")"; 
  }
'';
4 Likes

May I ask how to solve the issue where initExtra throws syntax error when @ is used.

For example, I am getting error: syntax error, unexpected '@' error because of a for loop.

for i in ${arr[@]}
do
done

I’ve tried slash, double quote, single quote, double single quote and I could not make it work.

It also failed when the function has :

So things like if ! [[ "${1:0:1}" =~ ^[1-3]+$ ]] won’t work.

If you’re using a string literal in Nix, Nix is trying to interpret the ${arr[@]} as its own string interpolation syntax. You’ll have to use an extra $, like $${arr[@]} or move it out into a separate file.

Thank you.

May I ask for an example on how to import a separate file to zsh? I am migrating from ubuntu. Currently these functions are stored on a aliases.zsh file and is sourced directly on .zshrc.

I am not too sure how to source extra files on nix…

You can use the following snippet in your nixos config

home-manager.users.john = {
  programs.zsh.initExtra = "source ${./aliases.zsh}";
};

where aliases.zsh is a file placed next to whatever file contains the snippet. You can use relative or absolute paths.

Like this aliases.zsh will be sourced whenever zsh starts.

There is also

  environment.shellAliases = {
    e = "sudo nano /etc/nixos/configuration.nix";
    u = "sudo nixos-rebuild switch";
    # etc
};

which will work in any shell.

2 Likes