Source Command - Execute Shell Scripts in Current Shell | Online Free DevTools by Hexmos

Execute shell scripts directly in your current shell with the Source command. Learn how to use

Source Command

Understanding the Source Command

The source command, also known as the dot command (.), is a fundamental shell built-in utility. It allows you to execute commands from a specified file directly within the current shell environment. This is distinct from running a script as a separate process, as source makes the script's variables, functions, and aliases available in your active shell session.

Basic Usage of Source

The primary function of the source command is to read and execute commands from a file. When you use source FILE, the shell interprets the contents of FILE as if you had typed them directly into your terminal. This is particularly useful for loading configuration files or setting up environment variables.

# Execute shell code residing within FILE as though you'd entered it in yourself.
source FILE

Shorthand for Source

In many shells, including Bash, the source command has a shorthand equivalent: the dot (.). This provides a more concise way to achieve the same result, especially in scripts where brevity is desired.

# The above can be written in short-hand, for the same effect, shell allowing.
. FILE

Passing Arguments with Source

The source command can also accept arguments, which are then passed to the script being executed. These arguments can be accessed within the sourced file using positional parameters like $1, $2, and so on. This enables dynamic execution of scripts based on different inputs.

# Source FILE with the given arguments to said file.
source FILE Argument_1 Argument_2 Argument_3 ...

When to Use Source

The source command is invaluable for several scenarios:

  • Loading Configuration Files: Many applications and development environments use configuration files (e.g., .bashrc, .profile) that need to be loaded into the current shell.
  • Setting Environment Variables: If you have a script that defines environment variables, sourcing it will make those variables available in your current session.
  • Defining Functions and Aliases: Sourcing a file can define custom shell functions or aliases that you can then use immediately.
  • Testing Scripts: It allows you to test parts of a script or its setup without executing it as a standalone process.

Understanding the source command is crucial for effective shell scripting and system administration. It provides a powerful mechanism for managing and executing shell code within your active environment.