#!/bin/bash # implementing a stack or a queue in bash. # push = pushes an element onto the stack # show = shows all elements in the stack # peek = shows the last element in the stack # peekf = shows the first element in the stack # pop = pops the last element off the stack # popf = pops the first element off the queue # isempty = returns 0 (false) if stack or queue has # elements in it; 1 (true) otherwise # example call: # if [[ $(outputstack_isempty) == 1 ]]; # then echo "is empty"; # else echo "is not empty"; # fi; # size = size of the stack outputstack=(); outputstack_push() { outputstack+=("$@"); } outputstack_show() { echo ${outputstack[@]}; } outputstack_peek() { echo "${outputstack[-1]}"; } outputstack_peekf() { echo $outputstack; } outputstack_pop() { unset outputstack[${#outputstack[@]}-1]; } # the following method is currently buggy in a for loop as of 02-25-2022 outputstack_popf() { unset outputstack[0]; } outputstack_isempty() { if (( ${#outputstack[@]} )); then echo 0; else echo 1; fi; } outputstack_size() { echo ${#outputstack[@]}; } # demo usage outputstack_push mercury; outputstack_push venus; outputstack_push earth; outputstack_show; if [[ $(outputstack_isempty) == 1 ]]; then echo "is empty"; else echo "is not empty"; fi; echo its size is $(outputstack_size); echo .; echo "------------"; popstring+=$(outputstack_peek)" "; outputstack_pop; outputstack_show; popstring+=$(outputstack_peek)" "; outputstack_pop; outputstack_show; popstring+=$(outputstack_peek)" "; outputstack_pop; outputstack_show; if [[ $(outputstack_isempty) == 1 ]]; then echo "is empty"; else echo "is not empty"; fi; echo $popstring;