我有一个 bash 脚本script.sh
,其中包含以下行:
sudo -u myusername sh ~/.profile
我可以从 shell 中调用,source ~/.profile
但这在脚本中不起作用,而此命令可以。它强制我当前的 shell 读取我的~/.profile
但是,我的~/.profile
包含以下几行:
if [ -f ~/.bashrc ]; then
source ~/.bashrc
fi
Run Code Online (Sandbox Code Playgroud)
因为它应该来源我的~/.bashrc
. 但是,当我运行时,script.sh
出现以下错误:
/home/username/.profile: 24: /home/username/.profile: source: not found
是否可以~/.bashrc
从 my ~/.profile
(本身是从另一个脚本调用的)获取我的文件而不更改 my~/.bashrc
或 my ~/.profile
?
这script.sh
会下载我的~/.profile
和~/.bashrc
文件并将它们放在正确的位置,因此我想在script.sh
下载这些文件后从内部获取这些文件,并让它们影响我用来运行的 shell 会话script.sh
该错误来自于尝试使用 执行~/.profile
文件sh
,该文件不理解source
(sh
使用.
(dot) 代替,它也适用于bash
和所有其他 POSIX shell)。
此外,执行~/.profile
不会设置该文件在执行它的 shell 中设置的环境变量。这是因为它在自己的子 shell 中运行。
子 shell(这是您执行~/.profile
而不是获取它时得到的)永远不会影响父 shell(您从中执行脚本的 shell)的环境。因此,除非您在文件中设置变量~/.profile
,否则您不能期望它们在脚本中设置source
。
运行sudo source ~/.profile
在这里没有帮助,因为sudo
它是当前 shell 的子进程。
相关的额外信息:
要为不是从交互式 shell 运行的脚本(其中~/.profile
和~/.bashrc
已获取)设置环境,请BASH_ENV
在调用脚本时将变量设置为适当的文件。这将在将控制权移交给脚本之前生成文件的bash
源代码。$BASH_ENV
例如:
BASH_ENV="$HOME/.profile" "$HOME/scripts/myscript.sh"
Run Code Online (Sandbox Code Playgroud)
仅当从非交互式 shell 会话(例如 cron 作业)调用脚本,并且需要访问设置的环境变量或任何源文件时,才需要执行此操作。~/.profile
~/.profile
在交互式 shell 会话中,BASH_ENV
不必以这种方式设置变量,并且脚本不需要获取~/.bashrc
或~/.profile
因为这些已经获取。