stacks.sh 1.4 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's avatar
Eric Coissac committed
44 45
  p="${1}[$(stacksize ${1})]=\"${2}\""
  eval "$p"
46 47 48
}

function popvalue() {
49 50 51 52 53 54 55 56 57 58
  local STACK="${1}"
  shift

  if [[ ! -z "${1}" ]]; then
    COMMAND="${1}="
  else
    COMMAND="echo "
  fi

  local s=$(stacksize ${STACK})
59 60 61 62
  if (( s==0 )); then
    return 1
  fi

63 64 65 66
  local valcmd="${COMMAND}\${${STACK}[\$(( s - 1 ))]}"
  eval $valcmd
  valcmd="unset ${STACK}[\$(( s - 1 ))]"
  eval $valcmd
67 68
  return 0
}