Difference between .bash_profile and .bashrc

If you are anything like me, you tried to automate repeating tasks using a bash script. You wrote it, tested it, and you want to be able to run it from any folder. So you used Goggle and found out that you need to set PATH to the folder where your scripts are. Now here comes the problem, some tutorials advise that you should export your PATH in .bash_profile, while others are recommending another file by the name .bashrc.

While others try to put them in any of these two files, and if it works, they move on; you want to know the difference between these two files. And that is why I like you. 😀

The answer to this is pretty simple. .bash_profile file is executed for login shells, while .bashrc is executed for interactive non-login shells.

I didn’t lie. I know that you are wondering what the difference between login and the non-login shell is. Bear with me; it is simple!

Login VS non-login shell

When you type username and password (login)in the console via ssh or on your machine .bash_profile is executed, and your shell is configured before the initial command prompt.

If you are already logged in and you open a new terminal window, then .bashrc is executed.

One exception to this rule is Mac OS X. On Mac Terminal.app runs a login shell by default for each new terminal window. That means that on Mac, you should always use .bash_profile.

One simple trick
I’m pretty sure that you don’t want to maintain two separate files when you set a PATH. To avoid this, you can source .bashrc from your .bash_profile file. In that way, you can only use the .bashrc file.

To make this happen, add these lines to .bash_profile

if [ -f ~/.bashrc ]; then
    source ~/.bashrc
 fi

Now even when you log in to your machine from console, .bashrc will be used.

Published by Stjepan

Just another software developer

Leave a comment

Your email address will not be published. Required fields are marked *