Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

linux

unix

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

source someOtherFile 

I know that causes the content of someOtherFile to execute, but what is the significance of 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)?

like image 532
Shailesh Tainwala Avatar asked Feb 17 '12 10:02

Shailesh Tainwala


People also ask

What does '- d do in Linux?

From the bash manpage (under CONDITIONAL EXPRESSIONS ): -d file True if file exists and is a directory. There's a whole host of these, letting you discover regular files, character-special files, whether files are writable, and so on.

What is D in shell script?

-d is a operator to test if the given directory exists or not. For example, I am having a only directory called /home/sureshkumar/test/. The directory variable contains the "/home/sureshkumar/test/" if [ -d $directory ]

What does the command source do?

In Linux systems, source is a built-in shell command that reads and executes the file content in the current shell. These files usually contain a list of commands delivered to the TCL interpreter to be read and run. This tutorial will explain how the source command works and when to use it.

Which of the following Unix command is used to display the content of a file from lines N to 1?

You can display the contents of a file using the cat command, which stands for concatenate. Let's say we have a file on our Desktop called myFile. txt, which contains the words one through fifteen (i.e., one, two, three… fifteen), with each number on a separate line.


2 Answers

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.

like image 147
Interrobang Avatar answered Sep 22 '22 14:09

Interrobang


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.

like image 42
Mithrandir Avatar answered Sep 24 '22 14:09

Mithrandir