当文件在 Unix/Linux 上下文中是 `source`-d 时会发生什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9326695/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 04:38:16  来源:igfitidea点击:

What occurs when a file is `source`-d in Unix/Linux context?

linuxunix

提问by Shailesh Tainwala

I've seen shell scripts that include a line such as:

我见过包含以下行的 shell 脚本:

source someOtherFile

I know that causes the content of someOtherFileto execute, but what is the significance of source?

我知道这会导致内容someOtherFile执行,但有什么意义source呢?



Follow-up questions: Can ANY script be sourced, or only certain type of scripts? Are there any side-effects other than environment variables when a script is sourced (as opposed to normally executing it)?

后续问题:可以获取任何脚本,还是只能获取某些类型的脚本?获取脚本时(与正常执行脚本相反),除了环境变量之外,是否还有其他副作用?

采纳答案by Interrobang

Running the command sourceon a script executes the script within the context of the current process. This means that environment variables set by the script remain available after it's finished running. This is in contrast to running a script normally, in which case environment variables set within the newly-spawned process will be lost once the script exits.

source在脚本上运行命令会在当前进程的上下文中执行脚本。这意味着脚本设置的环境变量在完成运行后仍然可用。这与正常运行脚本相反,在这种情况下,一旦脚本退出,在新生成的进程中设置的环境变量将丢失。

You can source any runnable shell script. The end effect will be the same as if you had typed the commands in the script into your terminal. For example, if the script changes directories, when it finishes running, your current working directory will have changed.

您可以获取任何可运行的 shell 脚本。最终效果与您在终端中键入脚本中的命令相同。例如,如果脚本更改目录,当它完成运行时,您当前的工作目录将更改。

回答by Mithrandir

If you tell the shell, e.g. bash, to read a file and execute the commands in the file, it's called sourcing. The main point is, the current process (shell) does this, not a new child process.

如果您告诉外壳程序(例如 bash)读取文件并执行文件中的命令,则称为采购。重点是,当前进程(shell)执行此操作,而不是新的子进程。

In BASH you can use the sourcecommand or simply .to source a file.

在 BASH 中,您可以使用该source命令或简单地.获取文件。

回答by Pratik Patil

sourceis a Unix command that evaluates the file following the command, as a list of commands, executed in the current context. You can also use .for sourcing the file.

source是一个 Unix 命令,它评估命令后面的文件,作为在当前上下文中执行的命令列表。您还可以.用于获取文件。

source my-script.sh;
. my-script.sh;

Both commands will have the same effect.

这两个命令将具有相同的效果。

In contrast, passing the script filename to the desired shell will run the script in a subshell, not the current context.

相反,将脚本文件名传递给所需的 shell 将在子 shell 中运行脚本,而不是当前上下文。