Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a stack in a shell script?

Tags:

stack

shell

sh

I need to create a stack in a shell script in order to push values to be processed in a loop. The first requirement is that this must be implemented in a portable manner, as I want to use the script as a portable installer (at least between Unix-like operating systems). The second requirement is that it needs to be able to be altered inside the loop, because new information can appear while the loop is processing an entry, in a recursive manner. The third requirement is that I have more than one line of information per entry (this is mostly a fixed number, and when it isn't it can be calculated based on the first line of information).

My attempt is to use a stack file:

#!/bin/sh

echo "First entry" > stack.txt
echo "More info for the first entry" >> stack.txt
echo "Even more info for the first entry" >> stack.txt

while read ENTRY < stack.txt; do
    INFO2=`tail -n +2 stack.txt | head -n 1`
    INFO3=`tail -n +3 stack.txt | head -n 1`

    tail -n "+4" stack.txt > stack2.txt

    # Process the entry...

    # When we have to push something:
    echo "New entry" > stack.txt
    echo "Info 2" >> stack.txt
    echo "Info 3" >> stack.txt

    # Finally, rebuild stack
    cat stack2.txt >> stack.txt
done

This works perfectly, except that it feels wrong. Is there a less "hacky" way to do this?

Thanks in advance for any help!

like image 906
Janito Vaqueiro Ferreira Filho Avatar asked Oct 22 '22 07:10

Janito Vaqueiro Ferreira Filho


1 Answers

Checkout the section here "Example 27-7. Of empty arrays and empty elements". Specifically the comments say, Above is the 'push' and The 'pop' is:

http://tldp.org/LDP/abs/html/arrays.html

If you want to encode multiple lines for each element I suggest you base64, or JSON encode the lines. You could also use url encoding or escape the characters using echo.

Since you require the usage of arrays, you may be able to use this example of arrays in sh:

http://www.linuxquestions.org/questions/linux-general-1/how-to-use-array-in-sh-shell-644142/

like image 120
benathon Avatar answered Nov 01 '22 08:11

benathon