Shell scripting is a powerful tool that allows you to automate tasks and execute commands in a Unix-like environment. Sourcing a file in a shell script means including the contents of another file within the current script, as if the contents were written directly in the script itself. This can be useful for reusing code, defining variables, and setting up environment configurations. In this tutorial, we’ll cover how to source a file in shell scripting.
Let’s say you have two shell scripts: script1.sh
and script2.sh
. script1.sh
is the main script that you want to source script2.sh
into.
- Create the
script2.sh
file: Open a text editor and create a new file calledscript2.sh
. This file will contain the code that you want to source intoscript1.sh
. For example, let’s define some variables inscript2.sh
:
# script2.sh
VAR1="Hello"
VAR2="World"
- Source
script2.sh
inscript1.sh
: In yourscript1.sh
file, you can use thesource
or.
(dot) command to include the contents ofscript2.sh
. Here’s an example:
# script1.sh
# Sourcing script2.sh
source script2.sh
# Accessing variables defined in script2.sh
echo "$VAR1 $VAR2"
The source
command and the .
(dot) command are equivalent and can be used interchangeably to source a file.
- Make
script1.sh
executable: Before executingscript1.sh
, make sure it has executable permissions. You can set the executable permission using thechmod
command:
chmod +x script1.sh
- Run
script1.sh
: To runscript1.sh
, use the following command:
./script1.sh
The script will output Hello World
, which is the result of accessing the variables defined in script2.sh
.
By sourcing script2.sh
into script1.sh
, you can reuse code, share variables, and perform other actions defined in the sourced file. This technique is particularly useful for modularizing your scripts and avoiding code duplication.
Remember to use relative or absolute paths when sourcing a file, depending on the location of the file you want to include. Also, ensure that the file you’re sourcing has the necessary executable permissions, and the correct file extension (e.g., .sh
for shell scripts).
That’s it! You’ve learned how to source a file in shell scripting. Have fun automating your tasks and building powerful scripts!