从zsh中输入bash时如何加载〜/ .bash_profile?

Bla*_*ard 35 unix macos bash shell user-profile

我已经使用了两年的bash,并试图通过自制软件在我的OS X上切换到zsh shell.我将我的默认(登录)shell设置为zsh,并通过查看当我启动终端时确认它设置正确,它是默认使用的zsh shell.

但是,当我尝试从zsh中输入bash shell时,它看起来没有加载~/.bash_profile,因为我无法使用别名运行我的命令,这是我~/.bash_profile喜欢的alias julia="~/juila/julia"等等.此外,提示不是我在文件中设置的而是返回bash-3.2$.

出于某些原因,当我将登录shell设置为bash,并从bash中输入zsh时,则~/.zshrc正确加载.

那么为什么每当我bash在zsh中运行时它都没有被加载?我~/.bash_profile是符号链接~/Dropbox/.bash_profile,以便与我的其他计算机同步.也许它会导致这个问题?

Yuc*_*ong 31

打开~/.zshrc,在文件的最底部添加以下内容:

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

每次打开终端时,它都会加载任何定义的内容~/.bash_profile(如果文件存在).有了它,您可以保留zsh(颜色等)的自定义设置.并且您可以将自定义shell设置保存在.bash_profile文件中.

这比使用bash -lIMO 要干净得多.

如果您更喜欢将设置放入.bashrc,或.bash_login,或者.profile,您可以为它们执行相同的操作.


Kei*_*son 25

交互式bash读取您~/.bash_profile的登录shell,~/.bashrc如果它不是登录shell,则读取它.

典型的.bash_profile将包含以下内容:

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

所以.bashrc可以包含由登录或非登录shell执行的命令.

如果你跑bash -l而不仅仅是bash,它应该读你的.bash_profile.

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


mkl*_*nt0 18

补充@Keith Thompson的优秀答案:

macOS:

正如@chepner简洁地说的那样(强调我的):

在OS X中,bash不用作初始[启动时]登录过程的一部分,并且Terminal.app(或其他终端仿真器)进程存在于任何预先存在的bash会话之外,因此每个新窗口[或选项卡 - read:interactive bash shell](默认情况下)将自己视为新的登录会话.

因此,一些OSX用户只能创建~/.bash_profile,而且从不打扰~/.bashrc,因为所有交互式bash shell都是登录 shell.

Linux:

在Linux上,情况通常是相反的: bash交互式创建的shell是[交互式] 非登录 shell,因此这很~/.bashrc重要.

因此,许多Linux用户只能处理~/.bashrc.


要维护适用于BOTH平台的bash配置文件,请使用@Keith Thompson提到的技术:

  • 把你的定义(别名,函数,...)放入 ~/.bashrc
  • 添加以下行 ~/.bash_profile
[[ -f ~/.bashrc ]] && . ~/.bashrc
Run Code Online (Sandbox Code Playgroud)


小智 13

复制〜/ .bash_profile中的内容并将其粘贴到〜/ .zshrc文件的底部.


Mus*_*les 6

对于刚刚安装zsh并希望其bash别名在zsh上运行的用户,请执行以下操作

  1. 像这样在vim中打开.zshrc文件

     vi ~/.zshrc
    
    Run Code Online (Sandbox Code Playgroud)
  2. 滚动到底部

  3. 单击“ i”以启用写入模式
  4. 告诉zsh必要时从bash_profile加载项目
    source ~/.bash_profile
    
    Run Code Online (Sandbox Code Playgroud)
  5. 像这样写然后退出
    :wq
    
    Run Code Online (Sandbox Code Playgroud)
  6. 像这样刷新您的zsh
    source ~/.zshrc
    
    Run Code Online (Sandbox Code Playgroud) 而已。现在,您在.bash_profile中保存的所有别名都可以在zsh中使用。


Yah*_*hel 5

对于MacO上的ZSH用户,我最终选择了一个班轮.

〜/ .zshrc的最底部,我添加了以下行:

bash -l
Run Code Online (Sandbox Code Playgroud)

它的作用是简单地加载.bash_profile设置(别名,函数,导出$ PATH,......)

如果你决定摆脱ZSH并回到朴素的BASH,你将恢复正常,没有任何麻烦.

  • 取而代之的是,在 `~/.zshrc` 文件的最底部,添加 `source ~/.bash_profile` 。 (4认同)
  • 这可以工作,但是会在zsh内创建另一个bash shell,并且您会丢失zsh功能和颜色。 (2认同)