source - macOS


Overview

source is a shell command used to execute commands from a file within the current shell environment. It is commonly used to load configuration files, define functions, or set environment variables.

Syntax

source [-v] [-e] [-h] file [arguments...]

Options/Flags

  • -v: Verbose mode. Displays the commands as they are executed.
  • -e: Exit on error. Stops the execution if an error occurs.
  • -h: Displays usage information.

Examples

Load a configuration file:

source /path/to/config.sh

Set environment variables:

source /path/to/set_env_vars.sh

Define functions:

source /path/to/functions.sh

Pass arguments to the sourced file:

source /path/to/script.sh arg1 arg2

Common Issues

  • Permission errors: Ensure you have read permissions for the file you are trying to source.
  • Syntax errors: Check the syntax of the sourced file for any errors.
  • Conflicting environment variables: If multiple sourced files set the same environment variable, the last value set will take precedence.

Integration

  • Bash: Use source to load Bash configuration files, e.g., .bashrc or .bash_profile.
  • Shell scripts: In shell scripts, use source to load shared functions or libraries.
  • Command chaining: Combine source with other commands to automate complex tasks, e.g., source /path/to/config.sh && command.
  • . (dot): Equivalent to source, but only executes commands within the current shell.
  • sh -s or bash -s: Alternative methods for executing commands from a file.