Do you still remember the regular expression that used to calculate prime numbers? The world of programming is so interesting that you will always be able to see something special. Have you ever thought that you can put your variables and functions into a class when writing shell scripts? Don't think this is impossible. No, I saw another object-oriented shell script on the Internet. Shell is not supported. You need to do something yourself. The hacker who can make this is really a hacker.
Of course, this is not really object-oriented, because it is just encapsulation and does not support inheritance and polymorphism. The most abnormal thing is that he still supports typeid!
Let's see how he did it. The following script may be confusing. I wanted to explain it. Later I thought about it. I 'd suggest you study it on your own. In fact, it's not hard to understand it. I 'd like to give you a few tips.
- As we can see, the following script defines functions such as class, func, VAR, and new, which are actually so-called keywords.
- Class is a function, mainly a record class name.
- Func and VaR are actually various variables with the same prefix of member function names and member variables.
- The new method records instances. Let's take a look at the for loop in the new function, where the core is.
The script is as follows:
# -------------------------------------------------------------------# OO support functions# Kludged by Pim van Riezen <pi@madscience.nl># -------------------------------------------------------------------DEFCLASS=""CLASS=""THIS=0 class() { 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; do eval "$var=\"\$INSTANCE_${THIS}_$var\"" done} loadfunc() { eval "funclist=\"\$CLASS_${CLASS}_FUNCTIONS\"" for func in $funclist; do eval "${func}() { ${CLASS}::${func} \"\$*\"; return \$?; }" done} savevar() { eval "varlist=\"\$CLASS_${CLASS}_VARS\"" for var in $varlist; do eval "INSTANCE_${THIS}_$var=\"\$var\"" done} typeof() { eval echo \$TYPEOF_$1} new() { local local cvar="$2" shift shift local id=$(uuidgen | tr A-F a-f | sed -e "s/-//g") eval TYPEOF_${id}=$class eval $cvar=$id local funclist eval "funclist=\"\$CLASS_${class}_FUNCTIONS\"" for func in $funclist; do eval "${cvar}.${func}() { local t=\$THIS; THIS=$id; local c=\$CLASS; CLASS=$class; loadvar; loadfunc; ${class}::${func} \"\$*\"; rt=\$?; savevar; CLASS=\$c; THIS=\$t; return $rt; }" done eval "${cvar}.${class} \"\$*\" || true"}