Creating classes and objects using bash scripting

You can try to do something like this

example.sh

#!/bin/bash

# include class header
. obj.h
. system.h

# create class object
obj myobject

# use object method
myobject.sayHello

# use object property
myobject.fileName = "file1"

system.stdout.printString "value is"
system.stdout.printValue myobject.fileName

obj.h

obj(){
    . <(sed "s/obj/$1/g" obj.class)
}

obj.class

# Class named "obj" for bash Object

# property
obj_properties=()

# properties IDs
fileName=0
fileSize=1

obj.sayHello(){
    echo Hello
}

obj.property(){
    if [ "$2" == "=" ]
    then
        obj_properties[$1]=$3
    else
        echo ${obj_properties[$1]}
    fi
}

obj.fileName(){
    if [ "$1" == "=" ]
    then
        obj.property fileName = $2
    else
        obj.property fileName
    fi
}

system.h

. system.class

system.class

system.stdout.printValue(){
    echo $($@)
}

system.stdout.printString(){
    echo $@
}

Link for reference: https://github.com/mnorin/bash-scripts/tree/master/objects
The point is you can’t create objects but you can emulate object-oriented programming in bash.

UPD:
After all these years I actually decided to add a hint for “inheritance”, because there is obviously no way to implement an actual inheritance, ALTHOUGH, combination may be visually presented like one. And to go this way we already have pretty much everything in the first example. With all the scripts above we can do a very simple thing like this:

obj2.h

obj2(){
    . <(sed "s/obj2/$1/g" obj2.class)
}

obj2.class

# Class named "obj2" for bash Object

obj2.sayGoodbye(){
    echo Goodbye
}

And the updated version of example.sh

#!/bin/bash

# include class headers
. obj.h
. obj2.h
. system.h

# create class object
obj myobject
obj2 myobject

# use object methods
myobject.sayHello
myobject.sayGoodbye # method "inherited" from obj2

myobject.fileName = "file1"

system.stdout.printString "value is"
system.stdout.printValue myobject.fileName

So, if you get lines obj myobject and obj2 myobject to look like inherit myobject from obj obj2, which is very simple, it will look a bit more like an inheritance (of course, it still won’t be one).

UPD2:
Following up on comments regarding making it work on bash3. Should be easy fix. Just replace $1 in obj.property with ${!1} and try to run it.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)