bash shell数组模拟栈运算(函数化)

将数组模拟栈运算函数化

包括push/pop/top/bottom/索引删除,存在检查等

 

array_test是测试和使用实例

 

#========== #1.0数组公函区 #用数组模拟栈 #出栈:array_pop #========== array_push() { local arrayname=$1 local newitem=$2 eval ${arrayname}'=("${'${arrayname}'[@]}" "$newitem" ) ' } array_pop() { local arrayname=$1 #use top #eval echo '${'${arrayname}'[$((${#'${arrayname}'[@]}-1))]}' #"use to avoid '*' transfer eval ${arrayname}'=("${'${arrayname}'[@]:0:$((${#'${arrayname}'[@]}-1))}") ' } array_top() { local arrayname=$1 #"use to avoid '*' transfer eval echo '"${'${arrayname}'[$((${#'${arrayname}'[@]}-1))]}"' } array_shift() { local arrayname=$1 #use bt #eval echo '${'${arrayname}'[0]}' eval ${arrayname}'=( "${'${arrayname}'[@]:1}" )' } array_bt() { local arrayname=$1 #"use to avoid '*' transfer eval echo '"${'${arrayname}'[0]}"' } array_unshift() { local arrayname=$1 local newitem=$2 eval ${arrayname}'=($newitem "${'${arrayname}'[@]}") ' } array_del_index() { local arrayname=$1 local index=$2 eval ${arrayname}'=(${'${arrayname}'[@]:0:$index} ${'${arrayname}'[@]:$(($index + 1))})' } #判断数组索引是否存在 #起始值是1 array_has_index() { local arrayname=$1 local index=${2-1} local max eval max='${#'${arrayname}'[*]}' eval test "$index" -ge 1 -a "$index" -le "$max" 2>/dev/null echo $? } array_test() { #declare echo declare null array :testarray local -a testarray echo array value testarray[*]: echo ${testarray[@]} #push echo push array item1.. array_push testarray item1 echo value item1,index is 0 testarray[0]: echo ${testarray[0]}; echo push array item2.. array_push testarray item2 echo value item1,index is 2 testarray[1]: echo ${testarray[1]}; echo array value testarray[*]: echo ${testarray[@]} #unshift echo unshift array item0 array_unshift testarray item0 echo array value testarray[*]: echo ${testarray[@]} #shift echo shift array item0 array_shift testarray item0 echo array value testarray[*]: echo ${testarray[@]} #pop echo pop array ; array_pop testarray ; echo array value testarray[*]: echo ${testarray[@]} #has index echo test tedex 0 array_has_index testarray 0 echo $? echo test tedex 1 array_has_index testarray 1 echo $? #del index echo del tedex 0 array_del_index testarray 0 echo $? echo array value testarray[*]: echo ${testarray[@]} } #测试 #array_test; #array_push aaa 111 #echo ${aaa[0]}

你可能感兴趣的:(bash shell数组模拟栈运算(函数化))