本文主要是介绍shell 简单oo编程,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
昨天突然有个疑问,linux shell能不能像power shell面向对象编程了。然后上班的时候就搜了下,还真有!
下面是拷贝过来的代码:
#!/bin/bash
# ---------------------------------------------------------------------------
# OO support functions
# Kludged by Pim van Riezen <pi@madscience.nl>
# ---------------------------------------------------------------------------
DEFCLASS=""
CLASS=""
THIS=0class() {DEFCLASS="$1"eval CLASS_${DEFCLASS}_VARS=""eval CLASS_${DEFCLASS}_FUNCTIONS=""
}static() {return 0
}func() {local varname="CLASS_${DEFCLASS}_FUNCTIONS"eval "$varname=\"\${$varname}$1 \""
}var() {local varname="CLASS_${DEFCLASS}_VARS"eval $varname="\"\${$varname}$1 \""
}loadvar() {eval "varlist=\"\$CLASS_${CLASS}_VARS\""for var in $varlist; doeval "$var=\"\$INSTANCE_${THIS}_$var\""done
}loadfunc() {eval "funclist=\"\$CLASS_${CLASS}_FUNCTIONS\""for func in $funclist; doeval "${func}() { ${CLASS}::${func} \"\$@\"; return \$?; }"done
}savevar() {eval "varlist=\"\$CLASS_${CLASS}_VARS\""for var in $varlist; doeval "INSTANCE_${THIS}_$var=\"\$$var\""done
}typeof() {eval echo \$TYPEOF_$1
}new() {local class="$1"local cvar="$2"shiftshiftlocal id=$(uuidgen | tr A-F a-f | sed -e "s/-//g")eval TYPEOF_${id}=$classeval $cvar=$idlocal funclisteval "funclist=\"\$CLASS_${class}_FUNCTIONS\""for func in $funclist; doeval "${cvar}.${func}() { local t=\$THIS; THIS=$id; local c=\$CLASS; CLASS=$class; loadvar; loadfunc; ${class}::${func} \"\$@\"; rt=\$?; savevar; CLASS=\$c; THIS=\$t; return $rt; }"doneeval "${cvar}.${class} \"\$@\" || true"
}# ---------------------------------------------------------------------------
# Example code
# ---------------------------------------------------------------------------# class definition
class Storpelfunc Storpelfunc setNamefunc setQualityfunc printvar namevar quality# class implementation
Storpel::Storpel() {setName "$1"setQuality "$2"if [ -z "$name" ]; then setName "Generic"; fiif [ -z "$quality" ]; then setQuality "Normal"; fi
}Storpel::setName() { name="$1"; }
Storpel::setQuality() { quality="$1"; }
Storpel::print() { echo "$name ($quality)"; }# usage
new Storpel one "Storpilator 1000" Medium
new Storpel two
new Storpel threetwo.setName "Storpilator 2000"
two.setQuality "Strong"one.print
two.print
three.printecho ""echo "one: $one ($(typeof $one))"
echo "two: $two ($(typeof $two))"
echo "three: $three ($(typeof $two))"
转载地址
这篇关于shell 简单oo编程的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!