bash(1) can be started in interactive mode or non-interactive mode. It can also act as a login shell or a non-login shell.
bash(1) is started in interactive mode by your terminal emulator and can also be started in interactive mode like this:
bash
bash -i
bash -ic 'echo Hello!'Refer: https://github.com/thoughtbot/til/blob/master/bash/bash_profile_vs_bashrc.md#:~:text=bashrc%20is%20sourced%20on%20every,with%20the%20%2D%2Dlogin%20option.&text=bash_profile%20is%20great%20for%20commands%20that%20should%20run%20only%20once%20and%20.
When you run a script through bash(1) or if you start it with the -c option, it will run in non-interactive mode:
bash script.sh
bash -c 'echo Hello!'bash(1) is instructed to act as a login shell when you first log in to your machine or when you start bash(1) with the --login or -l option.
.bashrc is sourced on every start in interactive mode when bash(1) does not act as a login shell.
.bash_profile is only sourced when bash(1) is started as an interactive login shell, or as a non-interactive shell with the --login option.
This means that .bash_profile is great for commands that should run only once and .bashrc for commands that should run every time you start a new shell.
For example, PATH customization should only happen once, since it is not an idempotent operation. Suppose something like this was in your .bashrc:
export PATH="$PATH:/addition"
Running these commands from a newly started interactive shell would produce the output below:
bash
bash
echo "$PATH"
/original_path:/addition:/addition:/additionSetting PATH in .bash_profile alleviates this problem.
Difference Between .bashrc and .bash_profile
.bash_profile is read and executed when Bash is invoked as an interactive login shell, while .bashrc is executed for an interactive non-login shell.
Use .bash_profile to run commands that should run only once, such as customizing the $PATH environment variable .
Put the commands that should run every time you launch a new shell in the .bashrc file. This include your aliases and functions , custom prompts, history customizations , and so on.
Typically, ~/.bash_profile contains lines like below that source the .bashrc file. This means each time you log in to the terminal, both files are read and executed.
if [ -f ~/.bashrc ]; then
. ~/.bashrc
fi
Most Linux distributions are using ~/.profile instead of ~/.bash_profile. The ~/.profile file is read by all shells, while ~/.bash_profile only by Bash
refer:
No comments:
Post a Comment