What Does Source Do In Linux : Script Execution In Current Shell

Running commands from a file in the current shell session is the role of the source command in Linux. If you have ever wondered what does source do in linux, this article breaks it down simply. You use source to execute a script without launching a new subshell. It is a built-in command in Bash and other Unix shells.

Think of source as a way to load settings or functions directly into your current terminal. When you run a script normally, it runs in a separate process. Source keeps everything in the same shell. This is crucial for tasks like updating environment variables or reloading configuration files.

What Does Source Do In Linux

Source reads and executes commands from a file in the current shell environment. It does not create a new process. Instead, it runs each line of the file as if you typed it directly. This means any variables, functions, or aliases defined in the file become available immediately.

For example, if you have a script that sets a variable, running it normally won’t keep that variable. But using source, the variable stays. This makes source ideal for configuration files like .bashrc or .profile.

How Source Differs From Normal Script Execution

When you run a script with ./script.sh or bash script.sh, it starts a new shell. That new shell has its own environment. Once the script finishes, the new shell exits, and any changes are lost. Source runs the script in the current shell, so changes persist.

  • Normal execution: Creates a subshell. Changes are temporary.
  • Source execution: Uses the current shell. Changes are permanent for the session.

This difference is why source is often used for setting up paths, exporting variables, or loading functions. It is also why you use source ~/.bashrc after editing that file.

Common Use Cases For The Source Command

Source is not just for reloading config files. It has several practical uses in daily Linux work. Here are the most common ones:

Reloading Shell Configuration Files

After editing .bashrc or .zshrc, you can apply changes without logging out. Just run:

source ~/.bashrc

This re-reads the file and updates your current session. It saves time and avoids restarting the terminal.

Setting Environment Variables

Many applications require environment variables. Instead of exporting them manually each time, you can put them in a file and source it. For example:

source /path/to/env_vars.sh

This loads all variables defined in that file into your shell. It is common in development environments for setting paths or API keys.

Loading Functions And Aliases

You can define functions or aliases in a separate file and source it. This keeps your main config file clean. For instance:

source ~/my_functions.sh

Now all those functions are available in your terminal. It is a great way to organize reusable code.

Running Scripts That Modify The Current Directory

If a script changes the working directory, using source ensures you end up in that new directory. Normal execution would leave you where you started. This is handy for scripts that navigate project folders.

How To Use The Source Command

Using source is straightforward. The syntax is:

source filename [arguments]

You can also use the shorthand dot (.) command:

. filename [arguments]

Both do the same thing. The dot version is older but still widely used. Here is a step-by-step example:

  1. Create a file called test.sh with the content: export MY_VAR="Hello"
  2. Run source test.sh in your terminal.
  3. Check the variable: echo $MY_VAR. It should print “Hello”.
  4. Now run bash test.sh and check again. The variable will be empty.

This simple test shows the difference. Source keeps the variable, while normal execution does not.

Passing Arguments To Source

You can pass arguments to the script when using source. Inside the script, these are accessible as $1, $2, etc. For example:

source myscript.sh arg1 arg2

This is useful for scripts that need parameters but still run in the current shell. It works the same as with normal scripts, except the environment persists.

Using Source With Functions

Source is excellent for loading function libraries. You can define multiple functions in one file and source it in your .bashrc. For instance:

source ~/lib/functions.sh

Then call any function from that file directly. This modular approach keeps your shell organized and reusable across different systems.

Practical Examples Of Source In Action

Let us look at real-world scenarios where source is invaluable. These examples will solidify your understanding of what does source do in linux.

Example 1: Updating PATH Variable

Suppose you install a custom tool in /opt/myapp/bin. You want to add it to your PATH. Create a file setpath.sh:

export PATH=$PATH:/opt/myapp/bin

Then source it:

source setpath.sh

Now you can run commands from that directory without specifying the full path. This change lasts for the current session.

Example 2: Activating Python Virtual Environments

Python virtual environments use a script called activate. You source it to enter the environment:

source venv/bin/activate

This changes your shell prompt and sets environment variables for that project. When you are done, you run deactivate to exit.

Example 3: Loading Docker Or Kubernetes Configurations

Many cloud tools provide scripts to set up authentication. For example, sourcing a file that exports AWS credentials:

source aws_creds.sh

This makes those credentials available for the current session without exposing them in your shell history.

Example 4: Running A Build Script That Sets Variables

If you have a build script that defines variables for compilation, using source ensures those variables are available for subsequent commands. This is common in complex build systems.

Common Mistakes And Pitfalls

Even experienced users make mistakes with source. Here are some to avoid:

  • Forgetting to source after editing config files. Changes won’t apply until you do.
  • Using source on a script that exits the shell. Some scripts contain exit commands, which will close your terminal.
  • Running source on a script with errors. It can break your current session.
  • Confusing source with bash or sh. They behave differently regarding environment.

Always test scripts in a subshell first if you are unsure. You can use bash -c 'source myscript.sh' to see effects without risking your session.

When Not To Use Source

Source is not always the best choice. Avoid it when:

  • You want the script to run independently without affecting your shell.
  • The script is long or complex and might cause side effects.
  • You are running untrusted code. Source gives full access to your environment.

For safety, only source files you trust and understand.

Source In Different Shells

The source command is available in Bash, Zsh, Ksh, and other POSIX-compliant shells. The syntax is similar, but there are minor differences. For example, in Zsh, source works the same as in Bash. In older shells like Sh, the dot command is preferred.

If you use Fish shell, the equivalent is source as well. However, Fish has its own syntax for functions and variables. Check your shell’s documentation for specifics.

Source Vs Dot Command

As mentioned, the dot (.) is a shorthand for source. They are identical in behavior. Some users prefer the dot for brevity. Others use source for clarity. Choose whichever you like, but be consistent in scripts.

One note: In some shells, the dot command might behave differently with arguments. Always test if you are unsure.

Advanced Source Techniques

Once you master the basics, you can use source in more advanced ways. Here are a few:

Conditional Sourcing

You can source files only if they exist. This prevents errors:

[ -f ~/custom.sh ] && source ~/custom.sh

This is common in .bashrc to load optional configurations.

Sourcing From A URL

You can source a script directly from a URL using curl or wget. For example:

source <(curl -s https://example.com/script.sh)

This downloads and executes the script in the current shell. Use with caution due to security risks.

Using Source In Functions

You can define a function that sources a file dynamically. This is useful for loading different environments:

load_env() {
  source "$1"
}

Then call load_env /path/to/env to load a specific configuration.

Debugging Source Scripts

If a sourced script causes issues, you can debug it. Use bash -x to trace execution, but remember that source runs in the current shell. Instead, run:

bash -x -c 'source myscript.sh'

This shows what each line does without affecting your session. You can also add set -x inside the script for verbose output.

Another trick is to source the script line by line manually to isolate problems. This is tedious but effective.

Performance Considerations

Sourcing a large file can slow down your shell startup. If your .bashrc sources many files, consider consolidating them. Use conditional sourcing to load only what is needed.

For example, only source development tools when you are in a project directory:

if [ -f .env ]; then
  source .env
fi

This keeps your shell responsive while still providing necessary configurations.

Security Implications

Since source runs code in your current shell, it has full access to your environment. Never source scripts from untrusted sources. A malicious script could steal data or modify your system.

Always review the contents of a script before sourcing it. Use cat or less to inspect it. If you must source from a URL, verify the source is legitimate.

Also, avoid sourcing scripts with sudo unless necessary. Sudo runs commands as root, and sourcing a root script can have unintended consequences.

Frequently Asked Questions

What is the difference between source and ./ in Linux?

Source runs the script in the current shell, while ./ runs it in a subshell. Source preserves changes to variables and the environment; ./ does not.

Can I use source in a shell script?

Yes, you can use source inside a script to load other files. This is common for including function libraries or configuration files.

Does source work in all Linux shells?

Source works in Bash, Zsh, Ksh, and most modern shells. In older shells like Sh, you may need to use the dot command instead.

How do I undo a source command?

There is no direct undo. You would need to manually reset variables or start a new shell session. Some scripts provide an unset function.

What does source do in linux for environment variables?

Source loads environment variables defined in a file into the current shell, making them available for all subsequent commands in that session.

Conclusion

Now you understand what does source do in linux. It executes commands from a file in the current shell, preserving changes to variables, functions, and the environment. This makes it essential for reloading configs, setting up development environments, and loading reusable code.

Use source wisely. It is a powerful tool that can save time and streamline your workflow. Always test scripts in a safe way first, and never source untrusted code. With practice, you will find source indespensable for daily Linux tasks.

Remember the key difference: source keeps changes, normal execution does not. This simple concept unlocks many possibilities. Start using source today to make your Linux experience more efficient.