如何从“bash -c”加载.bashrc

如何从“bash -c”加载.bashrc

尝试使用“bash -c”运行我的 .bashrc 中定义的函数。我最终收到错误“找不到命令”。如何让“bash -c”加载我的初始化文件?

答案1

您可以使用 使其成为交互式 shell -i,然后您的 ~/.bashrc 将被读取:

bash -i -c "echo \$EDITOR"

您可以做的另一件事是显式获取文件。如果您有/var/tmp/test内容:

export XXX=123

你也是

bash -c "source /var/tmp/test; echo \$XXX"

你会得到123回应。

答案2

另一种选择是设置$BASH_ENV变量:

   When bash is started non-interactively, to  run  a  shell  script,  for
   example, it looks for the variable BASH_ENV in the environment, expands
   its value if it appears there, and uses the expanded value as the  name
   of  a  file to read and execute.  Bash behaves as if the following com‐
   mand were executed:
          if [ -n "$BASH_ENV" ]; then . "$BASH_ENV"; fi
   but the value of the PATH variable is not used to search for  the  file
   name.

所以,你可以这样做:

BASH_ENV=~/.bashrc && bash -c 'your_function'

相关内容