source
Execute shell scripts in the current shell context
Syntax
source filename [arguments]
or
. filename [arguments]
Basic Usage
Source a configuration file
source ~/.bashrc
Executes the bashrc file in the current shell context.
Source using dot notation
. ~/.bashrc
Same as source, but more portable across shells.
Source with arguments
source config.sh production
Source from current directory
source ./local_config.sh
Key Differences
source vs Direct Execution
- source script.sh: Runs in current shell context
- ./script.sh: Creates new subshell
- Variables: Sourced scripts can modify current shell variables
- Functions: Functions defined in sourced scripts are available in current shell
- Environment: Changes persist after script execution
Practical Examples
Reload shell configuration
source ~/.bashrc
Load environment variables
source .env
Load custom functions
source ~/scripts/functions.sh
Load project configuration
source project_config.sh
Load with conditional logic
if [ -f ~/.local_config ]; then source ~/.local_configfi
Source multiple files
source ~/.aliasessource ~/.functionssource ~/.exports
Load development environment
source venv/bin/activate
Common Use Cases
When to Use source
- Configuration Files: Loading shell configuration files
- Environment Setup: Setting environment variables
- Function Libraries: Loading custom functions
- Development Tools: Activating virtual environments
- Project Setup: Loading project-specific configurations
- Alias Definitions: Loading custom aliases
Shell Compatibility
Shell Support
- bash: Supports both 'source' and '.'
- zsh: Supports both 'source' and '.'
- ksh: Supports both 'source' and '.'
- sh: May only support '.' (POSIX compliant)
- csh/tcsh: Uses 'source' command
Best Practices
When to Use
- Loading configuration files
- Setting up development environments
- Loading function libraries
- Reloading shell configurations
- Project-specific environment setup
Important Notes
- Use '.' for better POSIX compatibility
- Sourced scripts can modify your current shell environment
- Be careful when sourcing untrusted scripts
- Variables and functions persist after sourcing
- Use 'source' for bash-specific scripts
- Consider using '.' for portable scripts
- Always verify the content of scripts before sourcing