Creating classes and objects using bash scripting

Bash is a scripting language, that doesn't support OOP, so you can't. Try Python.

The only other thing you could do is have several arrays, but that's messy. Use the index to link them.


So I remember checking this question and answer a few years back .. and was thinking.... WHAT!?!?!

Then last week I took a closer look at @Maxims answer and then it became clear..

I have spent the last week and created a bash class transpiler and class loader for class object, with methods and other goodies.. all cause I wanted to create a terminal animation infrastructure:

two items being animated in the terminal

So while this is just a start I found this to be a SUPER cool and challenging adventure.. I hope my code would help someone else as well!!

BTW: Was tested only on MAC OS so some tweaking might be needed :)


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