【问题标题】:`source ~/.bash_profile` do not works inside a bash script`source ~/.bash_profile` 在 bash 脚本中不起作用
【发布时间】:2023-03-30 06:36:01
【问题描述】:

这是一个将 bash 文件移动到主页并使用源命令加载它的脚本。

# update.sh
#!/bin/bash
cp -f $PWD/bash_profile ~/.bash_profile
source ~/.bash_profile

它不起作用!它使用cp -f $PWD/bash_profile ~/.bash_profile 更新文件。

~/.bash_profile 中有一个新的 PS1 定义。文件已更新,但在打开新窗口之前没有发生任何更改。我需要在脚本执行后运行source ~/.bash_profile ...

是否可以在 bash 脚本中运行 source 命令?

【问题讨论】:

  • 如果你想更新你当前的 shell,你需要获取 bash 脚本。
  • 这是可能的,但由于在脚本中使用 source 而不是执行 .bash_profile 的原因相同,但没用。
  • shebang 必须是文件的第一行。
  • 不是一个新的答案,而是一些澄清。当你echo "PS1=${PS1}" after source ~/.bash_profile, you will see it is changed. The changes get lost, when your script update.sh` 完成。您可以使用source 使更改在当前 shell 中保持有效。

标签: bash dot-source


【解决方案1】:

来自 MangeshBiradar here:

使用. ./(点空格点斜杠)执行Shell脚本

使用“点空格点斜杠”执行shell脚本时,如下图所示,它将在当前shell中执行脚本,而不分叉子shell。

$ . ./setup.bash

也就是说,这会在当前 shell 中执行 setup.bash 中指定的命令,并为你准备好环境。

【讨论】:

  • 抱歉仍然无法在 bash 脚本中执行 source ~/.bash_profile
【解决方案2】:

bash 脚本在它自己的 shell 实例中运行。当 shell 退出时,新 shell 的所有环境变量(包括你的PS1)都会被遗忘。注意:这是出于安全考虑——如果 shell 可以改变其调用者的环境,它很容易通过给各种常用命令起别名来对该用户造成严重损害。

如果您运行source update.sh,它会像用户自己输入命令一样运行命令。 (或者你可以按照@JonathanMay 的建议使用.,它做同样的事情)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-16
    • 2011-03-02
    • 2011-09-04
    • 1970-01-01
    • 1970-01-01
    • 2017-04-30
    相关资源
    最近更新 更多