LnL7 / nix-darwin

nix modules for darwin
MIT License
3.13k stars 452 forks source link

bash: /etc/bashrc sources /etc/bashrc_$TERM_PROGRAM even for non-interactive login shells #325

Open lilyball opened 3 years ago

lilyball commented 3 years ago

I haven't installed nix-darwin yet, but I was reading through the bash module and I saw the following:

https://github.com/LnL7/nix-darwin/blob/c2124383f47315c23b0fbe8b75a1190b6d7929d0/modules/programs/bash/default.nix#L48-L66

On darwin, /etc/profile unconditionally sources /etc/bashrc, and it's up to /etc/bashrc to bail out of it's not interactive. This is what line 66 is doing, but the very first thing this does is load /etc/bashrc_$TERM_PROGRAM. My belief here is this is sourced before the Nix setup to mimic the normal Nix installation environment, except we want to always set up Nix for login shells so we do that before the interactive check.

The problem is, darwin ships a /etc/bashrc_Apple_Terminal that sets up a bunch of session history saving/restoring. This is only supposed to be done for interactive login shells and should not be done for non-interactive login shells. The net result of this is running something like bash -l -c 'echo foo' in Apple Terminal.app will be expected to print something like

Restored session: Wed Apr 28 23:12:12 PDT 2021
foo
Saving session...completed.

Probably the simplest fix is to do

-      [ -r "/etc/bashrc_$TERM_PROGRAM" ] && . "/etc/bashrc_$TERM_PROGRAM"
+      [[ $- != *i* && -r "/etc/bashrc_$TERM_PROGRAM" ]] && . "/etc/bashrc_$TERM_PROGRAM"
lilyball commented 3 years ago

After having installed nix-darwin, I can confirm this is indeed the case:

> bash -l -c 'echo yes'
Restored session: Wed Apr 28 23:42:18 PDT 2021
yes
Saving session...completed.
MatrixManAtYrService commented 10 months ago

I'm not sure how closely this is related (and sorry to distract if it's distant). I have nushell configured as my default shell. It works fine when I'm local, but if I ssh from another machine, attempts to run bash scripts fail will messages like:

/etc/bashrc: line 12: TERM_PROGRAM: unbound variable

and

/etc/bashrc: line 15: __ETC_BASHRC_SOURCED: unbound variable

running zsh as a subprocess and nu as a subsubprocess seems to straighten things out but then I have to exit thrice to get back to the ssh client machine.