source - Linux


Overview

The source command in Linux is a shell built-in command which is used to read and execute commands from a specified file in the current shell environment. This allows the script’s variables and functions to be available in the current shell session. It is primarily used for initializing script files and configuring shell environments across sessions.

Syntax

The basic usage of the source command is:

source filename [arguments]

Or its shorthand version using the dot operator:

. filename [arguments]

Where filename is the path to the script file you want to execute, and [arguments] are passed to the script.

Options/Flags

The source command does not have any specific options or flags apart from the filename and optional arguments to be passed to the script. The behavior of the command is straightforward: it reads and executes the content of the file in the current shell context.

Examples

  1. Basic Usage:

    source /path/to/script.sh
    

    This command sources the script.sh file, executing its contents.

  2. Passing Arguments:

    source script.sh arg1 arg2
    

    This executes script.sh with arg1 and arg2 as arguments, which can be handled by the script internally.

  3. Chaining Initialization Files:
    Assuming you have an initialization file for aliases (aliases.sh) and another for environment variables (env.sh), you can source both upon login:

    source aliases.sh
    source env.sh
    

Common Issues

  • File Not Found: Ensure the correct path is used. A common mistake is to use relative paths without knowing the current working directory.
  • Permissions: The file being sourced needs to be readable. Ensure proper permissions are set.
  • Syntax Errors in Script: Errors in the script will terminate the sourcing process. Check your scripts for errors.

Integration

Combining source with other commands enhances script automation and environment setup. For example, to dynamically configure the PATH on startup:

# File: extend-path.sh
export PATH="$PATH:/opt/new/bin"

# In .bashrc or .bash_profile
source extend-path.sh

This practice helps keep your .bashrc or .bash_profile clean and maintainable.

  • bash: Another way to execute a script but runs in a subshell.
  • . (dot command): Shorthand for source.
  • export: Often used within scripts that are sourced to set environment variables.

For more information about the source command, consult the documentation of the shell being used, typically Bash which can be found by running man bash in the terminal.