LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   Bash: How do I read data from a variable while that variable is being populated? (http://www.linuxquestions.org/questions/programming-9/bash-how-do-i-read-data-from-a-variable-while-that-variable-is-being-populated-803552/)

theaceoffire 04-22-2010 12:37 PM

Bash: How do I read data from a variable while that variable is being populated?
 
This is an attempt to clean out my scripts and to stop using temporary files to pass data.

I have two scripts: ScriptA (aka, "loudmouth"), and ScriptB (aka, "watcher"):

Code:

#!/bin/bash
#loudmouth.sh
i=1
while [ $i -lt 100 ];do
        echo "Look at me count!$i"
        sleep 1
        let "i=$i+1"
done

Code:

#!/bin/bash
#watcher.sh
oneline(){
        PROC=$1
        while [ -d /proc/$PROC ];do
                echo -en "\r" "`tail -n1 tmp.txt`"
        done
}

( eval $1 ) &>tmp.txt & oneline $!

And you activate my current example with:
Code:

>watcher.sh loudmouth.sh
I would like to have these same results without using tmp.txt AND without changing loudmouth... in other words, I would like to stream data into a variable, and randomly read out the last line of that variable.

^_^ SO, to recap:
I currently write to a file continuously, and randomly read the last line of that file to see how the process is progressing.

I would like to write to a variable continuously, and randomly read the most recent line of that variable to see how the progress is progressing.

Thanks!

ntubski 04-22-2010 01:40 PM

Not sure what reading "randomly" is.
Code:

#!/bin/bash
#watcher.sh

( eval $1 ) 2>&1 | while read LINE ; do
    echo -en "\r" "$LINE"
done


grail 04-22-2010 10:22 PM

@ntubski - I have heard of some issues with pipe being used this way hides this loop in another shell (or something like that)
Is it also possible to do it this way?

Code:

while read LINE; do
    echo -en "\r" "$LINE"
done < <(eval $1) 2>&1

Not a hundred percent on the formatting of the last part, so I am hoping you understand what i mean?

ntubski 04-23-2010 02:09 PM

Quote:

Originally Posted by grail (Post 3944705)
@ntubski - I have heard of some issues with pipe being used this way hides this loop in another shell (or something like that)

Yes, every command in the pipeline gets its own subshell.


Code:

while read LINE; do
    echo -en "\r" "$LINE"
done < <(eval $1 2>&1)

Seems to work, I moved the parenthesis to avoid an annoying error message on Ctrl+C.

tuxdev 04-23-2010 03:29 PM

This screams race condition.

BTW, do you know about the fairly ubiquitous utility "watch"? I believe it accomplishes what you want.


All times are GMT -5. The time now is 04:22 PM.