如何使OS X读取.bash_profile而不是.profile文件

che*_*ech 36 macos bash

我已经阅读了很多建议,而不是将您的自定义命令放在".profile"文件中.相反,为自己创建一个.bash_profile并添加别名等.

但是,当我打开新终端时,如果只有.bash_profile,则OS X不会导出/获取其中提到的命令.我必须手动获取.bash_profile.

如果我创建.profile文件,在打开一个新终端时,.profile中的所有命令都会被执行并且随时可用.

能帮助我理解,它是如何运作的?此外,何时使用.bashrc/.profile/.bash_profile文件.

谢谢!

And*_*man 75

根据OS X附带的手册页:

......它看起来~/.bash_profile,~/.bash_login~/.profile,按照这个顺序读取并执行从存在并且可读的第一个命令.--noprofile启动shell以禁止此行为时可以使用该选项.

它应该只~/.profile作为最后的手段,如果既不可读~/.bash_profile也不~/.bash_login可读.

在我的所有OS X系统上,我的~/.bash_profile设置为:

if [ -f ~/.bashrc ]; then
    source ~/.bashrc
fi
Run Code Online (Sandbox Code Playgroud)

强烈建议您在OS X上执行此操作,以便让bash ~/.bashrc像您期望的那样读取您的文件.

  • 如果您使用`zsh`而不是`bash`,请提醒您.终端将输出`.zshrc`而不是`.bash_profile`. (4认同)
  • 截至今天,OSX Cataline 中的默认终端 shell 是“zsh”,因此 @AlbertSamuel 的评论应该变成答案。 (3认同)

Dou*_*oug 46

苹果称

zsh (Z shell) 是所有新创建的用户帐户的默认 shell,从 macOS Catalina 开始。

因此,您应该使用以下命令验证您的默认 shell:

$ echo $SHELL
Run Code Online (Sandbox Code Playgroud)

如果结果是/bin/bash你的默认 shell 是 BASH,如果结果是/bin/zsh默认是 ZSH。

回到主页$ cd ~/并创建配置文件(如果它不存在)并使用以下命令对其进行编辑:

对于 bash:

$ touch .bash_profile
$ open .bash_profile
Run Code Online (Sandbox Code Playgroud)

对于 ZSH:

$ touch .zprofile
$ open .zprofile
Run Code Online (Sandbox Code Playgroud)

  • 你是一个英雄。我一直试图找出为什么 .bash_profile/.bashrc/.profile 半小时不起作用。 (2认同)

Mat*_*t S 26

您的终端shell也可能默认为sh而不是bash.你可以先验证这个:

$ echo $SHELL
/bin/tcsh
Run Code Online (Sandbox Code Playgroud)

要将此更改为bash,您可以进入终端 - >首选项 - >启动选项卡,并将"Shell Opens With:"从"Default login shell"更改为Command和value"/ bin/bash".

或者,您可以通过在命令提示符处执行以下命令来更改默认shell:

chsh -s bin/bash
Run Code Online (Sandbox Code Playgroud)

执行其中一个操作后,打开一个新的shell窗口,并且应该获取.bash_profile.

  • 我发现我想使用 sh 而不是 bash。我使用 zsh,我发现此评论很有帮助:https://github.com/robbyrussell/oh-my-zsh/issues/3807#issuecomment-187930190 - 基本上将 `source ~/.bash_profile` 添加到您的底部`~/.zshrc` 配置 (5认同)

Sab*_*ett 6

对于发现此内容的任何其他人,而不是 bash_profile,对于新版本的 mac,您可以使用.zshrc. 即,做

open .zshrc
Run Code Online (Sandbox Code Playgroud)

并在那里添加您需要的内容。


hon*_*lop 5

您可以使用zsh来解决问题。

Z shell(也称为zsh)是一个 Unix shell,它构建在bash(macOS 的默认 shell)之上,具有附加功能。它建议使用zshbash.

安装

  1. 使用 Homebrew 安装 zsh: $ brew install zsh
  2. 安装 Oh My Zsh: $ sh -c "$(curl -fsSL https://raw.githubusercontent.com/robbyrussell/oh-my-zsh/master/tools/install.sh)"
  3. 移动到.bash_profile设置.zshrc文件
  4. 要应用您所做的更改,您需要启动新的 shell 实例或运行: source ~/.zshrc


Bri*_*aid 5

如果您使用 zsh,则可以通过将以下行添加到 .zprofile 来获取 .bash_profile

if [ -f ~/.bash_profile ]; then
    source ~/.bash_profile
fi
Run Code Online (Sandbox Code Playgroud)