在bash shell脚本中重新加载.profile(在unix中)?

Ami*_*deh 119 unix bash shell .bash-profile

我是bash shell脚本的新手,遇到了挑战.我知道我可以通过以下方式重新加载我的".profile"文件:

. .profile
Run Code Online (Sandbox Code Playgroud)

但我正在尝试在我正在编写的bash脚本中执行相同的操作,但它只是无法正常工作.有任何想法吗?还有什么我可以澄清的吗?

谢谢

小智 177

试试这个来重装你当前的shell:

source ~/.profile
Run Code Online (Sandbox Code Playgroud)


小智 9

试试这个:

cd 
source .bash_profile
Run Code Online (Sandbox Code Playgroud)


twb*_*boc 5

尝试重新加载/源 ~/.profile 文件时会出现一些问题。[这里指的是 Ubuntu linux - 在某些情况下命令的细节会有所不同]

  1. 你是直接在终端还是在脚本中运行它?
  2. 你如何在脚本中运行它?

广告。1)

直接在终端中运行它意味着不会创建子shell。所以你可以使用两个命令:

source ~/.bash_profile
Run Code Online (Sandbox Code Playgroud)

或者

. ~/.bash_profile
Run Code Online (Sandbox Code Playgroud)

在这两种情况下,这都将使用 .profile 文件的内容更新环境。

广告 2)您可以通过调用启动任何 bash 脚本

sh myscript.sh 
Run Code Online (Sandbox Code Playgroud)

或者

. myscript.sh
Run Code Online (Sandbox Code Playgroud)

在第一种情况下,这将创建一个不会影响系统环境变量的子外壳,并且它们仅对子外壳进程可见。完成 subshel​​l 命令后,将不会应用任何导出等。这是一个常见的错误,会导致许多开发人员损失大量时间。

为了使您在脚本中应用的更改对全局环境生效,脚本必须运行

.myscript.sh
Run Code Online (Sandbox Code Playgroud)

命令。

为了确保您的脚本不在 subshel​​ 中运行,您可以使用此功能。(再次以 Ubuntu shell 为例)

#/bin/bash

preventSubshell(){
  if [[ $_ != $0 ]]
  then
    echo "Script is being sourced"
  else
    echo "Script is a subshell - please run the script by invoking . script.sh command";
    exit 1;
  fi
}
Run Code Online (Sandbox Code Playgroud)

我希望这能消除一些常见的误解!:D 祝你好运!