且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在ksh中优雅使用数组

更新时间:2022-03-11 21:12:40

不确定是否要... Kornshell可以处理关联数组和索引数组.

Not exactly sure what you want... Kornshell can handle both associative and indexed arrays.

但是,Kornshell数组是一维的.通过使用$()和eval,可以使用间接方法来模拟二维数组.我在较旧的Perl 4.x和Perl 3.x中做了几次,但这很痛苦.如果需要多维数组,请使用Python或Perl.

However, Kornshell arrays are one dimensional. It might be possible to use indirection to emulate a two dimensional array via the use of $() and eval. I did this a couple of times in the older Perl 4.x and Perl 3.x, but it's a pain. If you want multidimensional arrays, use Python or Perl.

唯一的事情是必须通过typedef命令声明数组:

The only thing is that you must declare arrays via the typedef command:

$ typeset -A foohash    #foohash is an associative array
$ typeset -a foolist    #foolist is an integer indexed array.

也许您的脚本可以看起来像这样

Maybe your script can look something like this

typeset -a sysname
typeset -a sysfunct

sysname[1] = "GENERATOR"
sysname[2] = "COOLER"
sysfunc[1] = "getGeneratorStatus"
sysfunc[2] = "getCoolerStatus"

for CURSYS in {1..2}
do
   CSYSNAME="${sysname[$CURSYS]}"
   CSYSFUNC="${sysfunc[$CURSYS]}"
   REPORT="$REPORT\n$CSYSNAME"
   CSYSSTATUS=$(eval "CSYSFUNC $(date)")
   REPORT="$REPORT\t$CSYSSTATUS"
done
echo $REPORT