在 bash 中同时使用“source”和“&”

kar*_*sag 4 unix bash shell

我只是在阅读 Unix shell 如何工作(bash特别是),我尝试了一些对我来说没有意义的东西。

据我了解,该source命令运行您在当前 shell 进程中提供的程序,而不是派生子进程。

另一方面,在运行&的进程完成之前,运行一个命令后跟将控制权返回给用户。如果不带 source 运行命令&,则当前 shell 在子进程退出之前将控制权返回给用户。

但是,当我创建了一个名为文件test.txt包含hello world,跑:

source /bin/cat test.txt
Run Code Online (Sandbox Code Playgroud)

......我明白了-bash: ????: command not found

同样,当我尝试使用加载我的 virtualenv 时

source ./venv/bin/activate &
Run Code Online (Sandbox Code Playgroud)

我刚刚得到了退出状态和进程 ID [1] 26489

这是怎么回事?特别是对于第二个命令。我糊涂了。

它是如何source工作的,当你使用它时会发生什么&

Dan*_*eck 5

source加载bash 脚本文件并在当前 shell 环境中解释它。cat不是 bash 脚本而是二进制程序文件,bash无法成功将其内容解释为脚本代码。除此之外,不是设计用于 bash 脚本source可能会出现错误行为。

source filename [arguments]

filename当前 shell 环境中读取和执行命令,并返回从filename. [...] 如果提供了任何参数,它们将在执行 filename 时成为位置参数。否则位置参数不变。返回状态是脚本中退出的最后一个命令的状态(如果没有执行命令,则为 0),如果filename未找到或无法读取则为false 。

当您使用 运行它时&,is 将在后台执行。对状态的任何更改只会在下次打印提示时显示,如下所示:

[1]+  Done                    source .bashrc
Run Code Online (Sandbox Code Playgroud)

如果你真的想启动一个替代shell的程序,看看exec.

   exec [-cl] [-a name] [command [arguments]]
          If command is specified, it replaces the shell.  No new  process
          is  created.  The arguments become the arguments to command.  [...]
Run Code Online (Sandbox Code Playgroud)