If/then statements in bashrc usign home-manager

Is it possible to put if/then statements in bashrc using home-manager? I’ve tried adding the following if/then statement to bashrcExtra & shellAliases with no luck, for example:

programs.bash = {
    enable = true;
    bashrcExtra = ''
      if command -v bat > /dev/null;
        then alias cat = "bat"
      elif command -v batcat > /dev/null;
        then alias cat = "batcat"
      fi
    '';
};

But when I source my bashrc, I get the following errors:

bash: alias: cat: not found
bash: alias: =: not found
bash: alias: bat: not found

Any suggestions?

I believe the syntax is alias foo=bar without spaces.

$ alias cat = "bat"
bash: alias: cat: not found
bash: alias: =: not found
bash: alias: bat: not found

$ alias cat="bat"
# success
1 Like

That worked! Thank you. What’s odd is that in my shellAliases I do have spaces on both sides of the equal signs. I wonder why it’s not consistent between the shellAliases and bashrcExtra.

shellAliases is just a Nix attribute set while bashrcExtra is a string that will be interpreted by Bash, so it needs to be both valid Bash syntax and a valid call to the alias builtin.

1 Like

Also you could just do

shellAliases = {
  cat = lib.getExe pkgs.bat;
  # Or
  cat = "${pkgs.bat}/bin/bat";
};

Ahh that makes sense. I’ll have to be more mindful of these nuances when updating my configuration files. Thank you for taking the time to explain that.