Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "source" the bin/activate script mean?

Tags:

bash

shell

This is in reference to a response I received that said I need to source this script in order to active the virtualenv.

No idea what that means, beginner here trying to figure out virtualenv.

like image 575
david Avatar asked Aug 28 '13 06:08

david


People also ask

What does source bin activate do?

bin/activate is the bash script being run. One other detail of source will be important. source runs the file provided in your current shell, not in a subshell. Thus it keeps the variables it creates or modifies around after the file is done executing.

What happens when you source a script?

Sourcing a script will run the commands in the current shell process. Changes to the environment take effect in the current shell. Executing a script will run the commands in a new shell process. Changes to the environment take effect in the new shell and is lost when the script is done and the new shell is terminated.

What does it mean to source a file?

When a file is sourced (by typing either source filename or . filename at the command line), the lines of code in the file are executed as if they were printed at the command line. This is particularly useful with complex prompts, to allow them to be stored in files and called up by sourcing the file they are in.

What is source in bash script?

The source command reads and executes commands from the file specified as its argument in the current shell environment. It is useful to load functions, variables, and configuration files into shell scripts. source is a shell built-in in Bash and other popular shells used in Linux and UNIX operating systems.


1 Answers

To source a script is to run it in the context of the current shell rather than running it in a new shell.

For example:

. myscript.sh

or:

source myscript.sh

(depending on which shell you're running).

If you run the script in its own shell, any changes it makes to the environment are in that shell rather than the one you call it from. By sourcing it, you can affect the environment of the current shell.

For example, examine the following transcript:

pax> cat script.sh 
export xyzzy=plugh
echo $xyzzy

pax> export xyzzy=twisty

pax> echo $xyzzy ; script.sh ; echo $xyzzy
twisty
plugh
twisty

pax> echo $xyzzy ; . script.sh ; echo $xyzzy
twisty
plugh
plugh

When you run the script (different shell), it sets xyzzy to plugh but that gets lost when the shell exits back to your original shell. You'll find the original value has been "restored" (in quotes because the original value was never actually changed, only a copy of it was).

When you source it, it's just as if you typed the commands within the current shell so the effect on the variables is persistent.

like image 174
paxdiablo Avatar answered Oct 18 '22 02:10

paxdiablo