This is a card in Dave's Virtual Box of Cards.

Shell startup files (.profile vs .*rc)

Created: 2024-11-30

Back to Unix.

I’m going to use Bash for these examples, but other shells seem to follow this pattern. I figured this out while doing some cool startup stuff with OpenBSD’s ksh (korn shell) in this blog entry: 10: Dev Shortcuts. You can see the experiments I ran there.

Is the mystery really this simple?

I don’t know about you, but every time I add entries to either .bash_profile or .bashrc, I always end up wondering if I’m using the correct file for the correct purpose.

The answer seems to be as simple as:

  • Environment variables can be exported to sub-shells.

  • Aliases and functions cannot.

(Bash can apparently export functions, but this is not a typical shell ability and I didn’t even know you could do that.)

The profile file is executed by the login shell

You can export a variable in .bash_profile such as $PATH and it will be available in all shells created under its process.

But aliases and functions defined in the profile will only be available in the login shell. And that’s probably not what you want.

The rc ("run commands") file is executed by all other shells

This is where you want your aliases and functions. They’ll be defined and available in all subshells.

A weird Bash quirk is that it doesn’t run .bashrc automatically in the login shell. It’s common practice to have your profile also execute .bashrc because, of course, your login shell is also an interactive shell.

Conclusion

Put your exported variables in your profile script. Put your aliases and functions in your rc script.