How to inherit properties and attributes from a parent script in BASH

Sayeed Anwar
2 min readApr 30, 2023

In BASH you can use a method called sourcing to accomplish this.

I have used this to write bootup scripts where certain names don’t change. Let me elaborate on this. There is more than one way to boot up a device it can be through SD Card, USB, or internal memory partition. All these different methods mount the same peripheral devices at bootup so these mounting names won’t change based on the bootup method defining the device name variables in a single place and calling it in every script helps.

First, define all your variables (attributes) and functions (properties) that you need in a single script file. Then source this script path in any script that will use these attributes and properties. This way you can reduce code redundancy, improve your maintainability, and overall increase your code clarity.

One way to make use of sourced functions is that you can call this function to set these global attributes based on some condition. Going with the bootup script example we can call these functions that can change these global attributes based on the bootup method.

Example code:

Run the child script which will compile the parent script for you when you source it. You can call the change variable function from the parent script to change the parent attribute.

parent_script.sh:

#!/bin/bash
# export is used to make this variable scope global; all the children scripts that use this script can use the property to modify this script
export var1=" hello"
# a property that will let the user set the variable from a child script
change_variable()
{
var1=$1
}

child_script.sh:

#!/bin/bash
source parent_script.sh
# should print "hello"
echo $var1
change_variable "hello world!"
# should print "hello world!" as the property has updated the attribute var1
echo $var1

--

--

Sayeed Anwar

Philosopher | Educator | Programmer | Problem Solver