stacks.sh 1.58 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

# LECA Bash library
#
# The LECA bash library provides a set of function used for helping
# development of bash script mainly to write job script on the luke
# cluster
#
# The files from the LECA Bash library must be sourced from your main script
#
#
# Provides function for manipulating a stack of values
# ====================================================
#
# Provides function:
#
16 17
#    - newstack <STACKNAME>
#      Creates a new stack named STACKNAME
18
#
19 20
#    - stacksize <STACKNAME>
#      Returns the count of element stored in the stack
21
#
22 23
#    - pushvalue <STACKNAME> <VALUE>
#      Adds the value VALUE at the end of the stack STACKNAME
24
#
25 26 27 28
#    - popvalue <STACKNAME>
#      Pops out the last pushed value of the stack.
#      If the stack is already empty the function returns nothing
#      and the return status is set to 1 instead of 0 usually
29 30
#

31 32 33 34
include logging
logdebug "Load stacks package"


35
function newstack() {
36
  eval declare -a "${1}"
37 38 39
}

function stacksize() {
40
  eval "echo \${#${1}[@]}"
41 42 43
}

function pushvalue() {
Eric Coissac committed
44 45
  p="${1}[$(stacksize ${1})]=\"${2}\""
  eval "$p"
46 47 48
}

function popvalue() {
49
  local __popvalue_STACK="${1}"
50 51 52
  shift

  if [[ ! -z "${1}" ]]; then
53
    local __popvalue_COMMAND="${1}="
54
  else
55
    local __popvalue_COMMAND="echo "
56 57
  fi

Eric Coissac committed
58 59
  local __popvalue_s=$(stacksize ${__popvalue_STACK})
  if (( __popvalue_s == 0 )); then
60 61 62
    return 1
  fi

Eric Coissac committed
63
  local __popvalue_valcmd="${__popvalue_COMMAND}\${${__popvalue_STACK}[\$(( __popvalue_s - 1 ))]}"
64
  eval $__popvalue_valcmd
Eric Coissac committed
65
  __popvalue_valcmd="unset ${__popvalue_STACK}[\$(( __popvalue_s - 1 ))]"
66
  eval $__popvalue_valcmd
67 68
  return 0
}