Introduction
Hello! Today I’ll explain the source command.
The source command loads configuration files or executes scripts in the current shell. You know when you edit .bashrc and think “I want to apply changes without restarting the terminal!”? That’s when you use this.
What is the source Command?
The source command executes a specified file in the current shell.
When you normally run a script, it starts a new shell process. But with source, it runs within your current shell. So variables and functions remain in your current shell.
Super handy, right?
Basic Syntax
|
|
or
|
|
A single period works too. It’s the POSIX shell compatible way.
Main Use Cases
| Use Case | Description |
|---|---|
| Load config files | Reload .bashrc or .bash_profile |
| Variable definition files | Load common variable definitions |
| Function libraries | Import functions for scripts |
| Environment setup | Set project-specific environment variables |
Usage Examples
Example 1: Reload .bashrc
|
|
or
|
|
Explanation:
After editing .bashrc, you can apply settings without restarting the terminal. I use this a lot.
Example 2: Load Environment Variable File
First, create an environment variable file.
|
|
Load it.
|
|
Output:
|
|
Variables are now set in the current shell.
Example 3: Load Function Library
|
|
Use in a script:
|
|
Output:
|
|
Example 4: Project Configuration File
|
|
Load when entering project directory:
|
|
Example 5: source with Arguments
|
|
Execute:
|
|
Output:
|
|
Tips & Notes
Difference Between source and ./
|
|
With ./, variables disappear when the script ends. With source, they remain.
Error Handling
If the file is not found with source, you get an error.
|
|
Path Specification
Both relative and absolute paths work.
|
|
Security Warning
Sourcing untrusted files is dangerous. The file contents execute in your current shell, so malicious code can harm your system.
|
|
Practical Usage
Structuring .bashrc
When .bashrc gets long, you can split it by functionality.
|
|
Makes it easier to maintain.
Switching Development Environments
|
|
Node.js nvm
nvm (Node Version Manager) also uses source.
|
|
Summary
Key points about the source command:
- Executes configuration files in the current shell
.(period) has the same meaning- Variables and functions remain in the current shell
- Super useful for reloading
.bashrc - Always check file contents before executing
When you edit configuration files, use source to apply changes immediately. Remember this - it’s really handy!