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

10 bash

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

Zel*_*lda 12

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

bash -i -c "echo \$EDITOR"
Run Code Online (Sandbox Code Playgroud)

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

export XXX=123
Run Code Online (Sandbox Code Playgroud)

你也是

bash -c "source /var/tmp/test; echo \$XXX"
Run Code Online (Sandbox Code Playgroud)

你会得到123回应。


ter*_*don 8

另一种选择是设置$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.
Run Code Online (Sandbox Code Playgroud)

所以,你可以这样做:

BASH_ENV=~/.bashrc && bash -c 'your_function'
Run Code Online (Sandbox Code Playgroud)