14

I have a .bashrc file on Mac OS in which I set some aliases. After I make it and I type source .bashrc, the aliases work perfectly. However if open another shell, my shortcut command will not be recognized and I need to do source .bashrc again. How can it make it once and for all?

BenMorel
  • 34,448
  • 50
  • 182
  • 322
user1849043
  • 339
  • 1
  • 3
  • 13

5 Answers5

9

Terminal and iTerm 2 open new shells as login shells by default. When Bash is opened as a login shell, it reads ~/.bash_profile but not ~/.bashrc.

See https://www.gnu.org/software/bash/manual/html_node/Bash-Startup-Files.html:

Invoked as an interactive login shell, or with --login

When Bash is invoked as an interactive login shell, or as a non-interactive shell with the --login option, it first reads and executes commands from the file /etc/profile, if that file exists. After reading that file, it looks for ~/.bash_profile, ~/.bash_login, and ~/.profile, in that order, and reads and executes commands from the first one that exists and is readable. The --noprofile option may be used when the shell is started to inhibit this behavior.

So either:

  1. Use ~/.bash_profile instead of ~/.bashrc.
  2. Use ~/.bashrc but source ~/.bashrc from ~/.bash_profile.
  3. Tell your terminal application to open new shells as non-login shells.

I have done the last two. For example tmux and the shell mode in Emacs open new shells as non-login shells. I still source ~/.bashrc from ~/.bash_profile because Bash is opened as a login shell when I ssh to my computer.

Community
  • 1
  • 1
Lri
  • 26,768
  • 8
  • 84
  • 82
6

If you are on Mac and you want to source ~/.bash_profile automatically on when a terminal is opened

  1. Open Terminal
  2. Go to Preferences
  3. Go to Profiles
  4. Select then open shell
  5. Add this command source ~/.bash_profile in Run command enter image description here
3

If you want to source your bash_profile file everytime you open a new tab you can also set up a command on Iterm.

Go to Preferences -> Profiles -> General -> Command

iter-bash-profile

alakin_11
  • 689
  • 6
  • 12
2

I encounter the same problem and I solve it. The macos have shift the default shell from bash to zsh.

So I try to modify the ~/.bashrc and ~/.bash_profile and source that but just work to current Terminal.

The fact is you should modify the ~/.zshrc profile file.

Try it my friend!

Pandy
  • 138
  • 1
  • 4
  • I spent so much time looking for a solution but nobody mentioned that mac shifted to `~/.zshrc`. Top answer – George May 18 '22 at 08:55
-1
  1. nano ~.bash_profile (Opens the ~.bash_profile)

  2. aliasname(){ ssh user@ipaddress }(You can add any command for the alias, I have shown the ssh command for a particular IP address)

  3. Press Control+O and press Enter (Save the file). Control+X(Exit nano editor)

  4. source .bash_profile

Now you have a persistent command across all the terminals whenever you type aliasname.