Container types in shell script


Shell script does not support container types like map, set, or queue, though with a third-party lib, presented here, we can use them in our scripts.

From time to time we need map, queue or any other kind of collections during our work. Shell script is definitely not the right choice to write applications but it may happen that we need some of the previously mentioned types to help our work.

Though shell script weakly supports types at all, we can use queues, stacks, maps in an easy, readable, and maintanable way. In this post I present a module that can provide these functionalities to us. And we still in shell script.

Container Types

All types are collection types, like map, queue, stack or set or as we call it aggregate since set is a built-in function.

Map

Map provides a container over key-value pairs with well-known methods.

As a usage, see below:

source 'map.sh'

map create fruits
map add fruits apple 2 # where apple is key and 2 is value
map size fruits # returns 1
map get fruits apple # 2
map values fruits # 2

Map’s API: https://github.com/torokmark/utils.sh/wiki/Map

Aggregate

Aggregate is none other than the classic set. All elements are unique in this datastructure.

source 'aggregate.sh'

aggregate add fruits apple
aggregate add fruits apple
aggregate size fruits # 1
aggregate empty fruits # false

aggregate contains fruits vegetables union_set
aggregate intersection fruits vegetables intersection_set
aggregate difference fruits vegetables

aggregate destroy fruits

Aggregate’s API: https://github.com/torokmark/utils.sh/wiki/Aggregate

Stack

Stack is a classic LIFO datastructure with its well-known methods.

source 'stack.sh'

stack create fruits
stack push fruits apple
stack push fruits pear
stack size fruits # 2
stack top fruits # pear
stack empty fruits # false
stack destroy fruits

Stack’s API: https://github.com/torokmark/utils.sh/wiki/Stack

Queue

Queue is a FIFO datastructure with appropriate methods to put, remove data or destroy the queue itself.

source 'queue.sh'
# I create a queue called fruits
queue create fruits
# put an element to queue
queue enqueue fruits apple
queue peek fruits
queue destroy fruits

Queue’s API: https://github.com/torokmark/utils.sh/wiki/Queue

Source code is available here: https://github.com/torokmark/utils.sh
Github page is avaliable here: https://torokmark.github.io/utils.sh