stacks.sh 1.71 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
  logdebug "New stack ${1} created"
37
  eval declare -a "${1}"
38 39 40
}

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

function pushvalue() {
45
  logdebug "New value pushed on stack ${1}"
Eric Coissac committed
46 47
  p="${1}[$(stacksize ${1})]=\"${2}\""
  eval "$p"
48 49 50
}

function popvalue() {
51
  local __popvalue_STACK="${1}"
52
  shift
53
  logdebug "New value poped from stack ${__popvalue_STACK}"
54 55

  if [[ ! -z "${1}" ]]; then
56
    local __popvalue_COMMAND="${1}="
57
  else
58
    local __popvalue_COMMAND="echo "
59 60
  fi

Eric Coissac committed
61 62
  local __popvalue_s=$(stacksize ${__popvalue_STACK})
  if (( __popvalue_s == 0 )); then
63 64 65
    return 1
  fi

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