Rogue
Rogue

Reputation: 779

Capture stdout for a long time in bash

I'm using a script which is calling another, like this :

# stuff...
OUT="$(./scriptB)"
# do stuff with the variable OUT

Basically, the scriptB script displays text in multiple time. Ie : it displays a line, 2s late another, 3s later another and so on.

With the snippet i use, i only get the first output of my command, i miss a lot. How can i get the whole output, by capturing stdout for a given time ? Something like :

begin capture
./scriptB
stop capture

I don't mind if the output is not shown on screen.

Thanks.

Upvotes: 0

Views: 64

Answers (2)

shellter
shellter

Reputation: 37268

Some of your output seems to be coming on the STDERR stream. So we have to redirect that as needed. As in my comment, you can do

{ ./scriptB ; } > /tmp/scriptB.log 2>&1

Which can almost certainly be reduced to

./scriptB  > /tmp/scriptB.log 2>&1

And in newer versions of bash, can further be reduced to

 ./scriptB >& /tmp/scriptB.log

AND finally, as your original question involved storing the output to a variable, you can do

 OUT=$(./scriptB > /tmp/scriptB.log 2>&1)

The notation 2>&1 says, take the file descriptor 2 of this process (STDERR) and tie it (&) into the file descriptor 1 of the process (STDOUT).

The alternate notation provided ( ... >& file) is a shorthand for the 2>&1.

Personally, I'd recommend using the 2>&1 syntax, as this is understood by all Bourne derived shells (not [t]csh).

As an aside, all processes by default have 3 file descriptors created when the process is created, 0=STDIN, 1=STDOUT, 2=STDERR. Manipulation of those streams is usually as simple as illustrated here. More advanced (rare) manipulations are possible. Post a separate question if you need to know more.

IHTH

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201439

If I understand your question, then I believe you can use the tee command, like

./scriptB | tee $HOME/scriptB.log

It will display the stdout from scriptB and write stdout to the log file at the same time.

Upvotes: 1

Related Questions