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 is the main script that you want to source
- Create the
script2.shfile: Open a text editor and create a new file called
script2.sh. This file will contain the code that you want to source into
script1.sh. For example, let’s define some variables in
# script2.sh VAR1="Hello" VAR2="World"
script1.sh: In your
script1.shfile, you can use the
.(dot) command to include the contents of
script2.sh. Here’s an example:
# script1.sh # Sourcing script2.sh source script2.sh # Accessing variables defined in script2.sh echo "$VAR1 $VAR2"
source command and the
. (dot) command are equivalent and can be used interchangeably to source a file.
script1.shexecutable: Before executing
script1.sh, make sure it has executable permissions. You can set the executable permission using the
chmod +x script1.sh
script1.sh: To run
script1.sh, use the following command:
The script will output
Hello World, which is the result of accessing the variables defined in
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!