Skip to content

Instantly share code, notes, and snippets.

@Phil-Venter
Created August 29, 2025 07:00
Show Gist options
  • Select an option

  • Save Phil-Venter/ff3590526cab54f5175f3d2a5af69bc4 to your computer and use it in GitHub Desktop.

Select an option

Save Phil-Venter/ff3590526cab54f5175f3d2a5af69bc4 to your computer and use it in GitHub Desktop.
Simple OOP bash
#!/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