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

前端 未结 3 861
夕颜
夕颜 2020-12-07 13:50

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

source someOtherFile

I know that causes the content of someOtherFile to

相关标签:
3条回答
  • 2020-12-07 14:17

    Running the command source on 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.

    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.

    0 讨论(0)
  • 2020-12-07 14:21

    source is 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 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.

    0 讨论(0)
  • 2020-12-07 14:32

    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.

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

    0 讨论(0)
提交回复
热议问题