【发布时间】:2012-05-06 10:42:01
【问题描述】:
我有几个 bash 脚本,我想确保它们默认运行,我目前将它们存储在我的 mac 上的 ~/.profile 中。那是存放它们的错误地方吗?我听说过其他人并尝试过(如~/.bashrc、~/.bash_profile 等),但它们似乎不起作用。
所有这些之间有什么区别,我将脚本放入哪个脚本以便它在运行时进行配置,而我每次打开终端时都不必调用$ source ~/.profile?
【问题讨论】:
我有几个 bash 脚本,我想确保它们默认运行,我目前将它们存储在我的 mac 上的 ~/.profile 中。那是存放它们的错误地方吗?我听说过其他人并尝试过(如~/.bashrc、~/.bash_profile 等),但它们似乎不起作用。
所有这些之间有什么区别,我将脚本放入哪个脚本以便它在运行时进行配置,而我每次打开终端时都不必调用$ source ~/.profile?
【问题讨论】:
如果 ~/.bash_profile 和 ~/.profile 都存在,则 bash 在作为交互式登录 shell 调用时只会读取 ~/.bash_profile。
https://www.gnu.org/s/bash/manual/html_node/Bash-Startup-Files.html:
作为交互式登录 shell 调用,或使用 --login
当 Bash 作为交互式登录 shell 或作为带有
--login选项的非交互式 shell 调用时,它首先从文件/etc/profile中读取并执行命令,如果该文件存在的话。读取该文件后,它会按顺序查找~/.bash_profile、~/.bash_login和~/.profile,并从第一个存在且可读的文件中读取并执行命令。[...]
作为交互式非登录 shell 调用
当一个不是登录 shell 的交互式 shell 启动时,Bash 从
~/.bashrc读取并执行命令,如果该文件存在的话。
~/.profile 也被其他 shell 使用。
Terminal 和 iTerm 默认打开新的 shell 作为登录 shell(通过执行类似 login -pf $USER 的东西),但是许多 GNU/Linux 终端应用程序打开新的 shell 作为非登录 shell。 OS X 用户经常使用~/.bash_profile 而不是~/.bashrc。
【讨论】:
+-----------------+
| |
interactive shell -->| ~/.bashrc |
| |
+-----------------+
interactive shell 将自动获取~/.bashrc。
看看Should the .bashrc in the home directory load automatically?
【讨论】:
source ~/.bashrc 附加到~/.bashrc_profile。
我做了这些来纠正这个问题:
cat .bash_profile >> .profile
rm .bash_profile
替代方案是:
echo "source ~/.profile" >> .bash_profile
【讨论】:
确保如果您在 .bashrc 中执行 source ~/.profile 注释或删除任何命令(在 .profile 中)以在您的 .profile 中调用或获取 .bashrc,否则它将永远循环,您将永远不会得到提示。
【讨论】:
不同的 bash 设置会根据它们的配置自动获取不同的文件。始终来源的几乎通用文件是~/.bashrc - 这是一个 bash 核心内容,它将加载此文件。在该文件中,您应该将您的行添加到source ~/.profile,然后您就可以开始了!
-编辑-
来自我的 Linux 和我同事的 Mac:
$ echo "echo hello" >> ~/.profile
$ echo "source ~/.profile" >> ~/.bashrc
$ bash
Hello
$
【讨论】:
~/.bash_login 调用的,但这不一定是这样......所以你不能指望 .bashrc 被调用。请参阅@kev 帖子中的链接。