Creating and Sourcing a Basic Script
In this step, we will create a simple script file and use the source
command to execute it in our current shell environment. This will help us understand how source
differs from regular script execution.
When you run a script normally (using ./script.sh
), the shell creates a new subprocess to execute the script. Any variables or functions defined in that script only exist within that subprocess and disappear when the script finishes. However, when you use the source
command (or its shorthand .
), the commands in the script execute in your current shell environment, allowing variables and functions to persist after the script completes.
Let's create a basic script to demonstrate this concept:
1. Navigate to the project directory
First, make sure you're in the correct directory:
cd ~/project
2. Create a simple script file
Create a new file named variables.sh
using the nano editor:
nano variables.sh
Add the following content to the file:
#!/bin/bash
## This script sets an environment variable
export WEATHER="Sunny"
echo "The weather is now set to: $WEATHER"
Press Ctrl+O
to save the file, then Enter
to confirm the filename, and finally Ctrl+X
to exit nano.
3. Make the script executable
Before we can run the script, we need to make it executable:
chmod +x variables.sh
4. Run the script normally
First, let's run the script in the traditional way:
./variables.sh
You should see output similar to:
The weather is now set to: Sunny
Now, check if the WEATHER
variable exists in your current shell:
echo $WEATHER
You'll likely see nothing output, or an empty line. This is because the variable was only set in the subprocess that ran the script, not in your current shell.
5. Source the script
Now, let's use the source
command to run the script:
source variables.sh
You'll see the same output:
The weather is now set to: Sunny
Check the WEATHER
variable again:
echo $WEATHER
This time, you should see:
Sunny
The WEATHER
variable now exists in your current shell because you used the source
command to execute the script.
6. Using the shorthand notation
You can also use the dot (.
) shorthand notation for the source
command:
. variables.sh
This will produce the same result as using source variables.sh
.