2

It should be noted that I am on MacOS 12.0.1 and I'm looking to add some persistent environment variables.

I have seen posts about creating and adding to ~/.bashrc or ~/.bash_profile but I'm not sure which is which. That being said, anything I add there only works after I use . ./bash_profile or source ./bash_profile once the terminal loads. I have also tried adding source ./bash_profile to either bashrc or bash_profile but that gives me a open too many files error.

Thanks in advance

bmike
  • 235,889

2 Answers2

3

This is one of the areas where Linux and macOS differ so a lot of articles you find only partially apply to macOS. Mainly, on macOS, each Terminal tab runs a login shell.

  • For login shells, bash reads ~/.bash_profile or (if this is missing) ~/.profile.
  • For interactive shells, bash reads ~/.bashrc.

So on macOS it doesn't actually matter which of ~/.bashrc or ~/.bash_profile you choose. It helps to be consistent though and stick to one or the other.

To make environment variables available in all future session, just add them to the file of your choosing:

MYVAR='Hello, world'; export MYVAR

PS: Personally I have test -f ~/.bashrc && . ~/.bashrc in .profile and all definitions in ~/.bashrc. This covers both worlds (at the cost of always loading some stuff which only is applicable to Linux or macOS) and IMHO is good enough for personal use.

nohillside
  • 100,768
  • Apple doesn't change how/when bash reads its startup files. The INVOCATION section of the man page exists for a reason. – Marc Wilson Jan 30 '22 at 16:40
  • "This is one of the areas where Linux and macOS differ"... but they don't. The shell works the same on both. I know what you meant and you know what you meant but I doubt the OP does. – Marc Wilson Jan 30 '22 at 18:43
  • So in order to test this theory I added a simple echo command inside of each of the profile, bash_profile, bashrc and none of them run when I start, perhaps I'm placing the files incorrectly? – Talking Mango Jan 31 '22 at 06:08
0

From Apple developer documentation archives Login Scripts:

OS X provides support for login scripts and environment property lists to allow you to set environment variables and aliases that are automatically set whenever you run a new shell. There are two ways to do this:

Bourne shell (bash, zsh, and so on):

To persistently set environment variables and add aliases, you can add the appropriate alias, variable assignment, and export commands to the following files:

  • ~/.profile—executed automatically for all login shells.
  • ~/.bash_profile—similar to .profile, but only runs for bash login shells.
  • ~/.bashrc and ~/.zshrc—executed automatically for all non-login bash or zsh shells (when you explicitly type bash or zsh on the command line or run a script that starts with #!/bin/bash or #!/bin/zsh).

You may also find it useful to create a .bashrc file that sources your .profile file. For example:

. $HOME/.profile