Created
August 29, 2025 07:00
-
-
Save Phil-Venter/ff3590526cab54f5175f3d2a5af69bc4 to your computer and use it in GitHub Desktop.
Simple OOP bash
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/bin/bash | |
| Object() { | |
| kind=$1 ; this=$2 ; shift 2 | |
| for arg in "$@"; do | |
| read ARG_KEY ARG_VALUE <<< $(echo "$arg" | sed -E "s/(\w+)=(.*?)/\1 \2/") | |
| read FUNC <<< $(echo "$arg" | sed -E "s/fn_(\w+)$/\1/") | |
| if [[ ! -z "$ARG_KEY" && ! -z "$ARG_VALUE" ]]; then | |
| export ${this}_$ARG_KEY="$ARG_VALUE" | |
| elif [[ ! -z "$FUNC" && "$FUNC" != "$this" ]]; then | |
| export ${kind}_fn_$FUNC=$FUNC | |
| fi | |
| done | |
| } | |
| Account() { | |
| Object account "$@" | |
| Object account $1 fn_display | |
| Object account $1 fn_deposit | |
| } | |
| display() { | |
| this=$1 | |
| name=${this}_name | |
| balance=${this}_balance | |
| greeting=$2 | |
| echo "$greeting, ${!name}. Your balance is ${!balance}" | |
| } | |
| deposit() { | |
| this=$1 | |
| current=${this}_balance | |
| amount=$2 | |
| export ${this}_balance=$(($current + $amount)) | |
| } | |
| Account accountA name=First\ Name balance=100 | |
| $account_fn_deposit accountA 50 | |
| $account_fn_deposit accountA 50 | |
| $account_fn_display accountA Hi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment