Home Linux Shell Scripting Sourcing a file

Shell Scripting Sourcing a file

by Anup Maurya
13 minutes read

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.

  1. Create the script2.sh file: 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:
# script2.sh
VAR1="Hello"
VAR2="World"
  1. Source script2.sh in script1.sh: In your script1.sh file, you can use the source or . (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"

The source command and the . (dot) command are equivalent and can be used interchangeably to source a file.

  1. Make script1.sh executable: Before executing script1.sh, make sure it has executable permissions. You can set the executable permission using the chmod command:
chmod +x script1.sh
  1. Run script1.sh: To run script1.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!

related posts

Leave a Comment