Prajwal
Prajwal

Reputation: 673

Order mismatch between stdout and stderr in bash

I am executing a bash command in interactive shell as ./somescript.sh

It gives output as

OS platform is: linux2
killall agent
agent: no process killed

where third line comes from stderr.

But when I execute in the subshell as

var=$('./somescript.sh' 2>&1)
agent: no process killed
OS platform is: linux2
killall agent

Why did the agent: no process killed is printing in the first line now? How can I make it consistent to align both of them?

Edit: However when I did , var=$('./somescript.sh' 1>&2) I can see that it's giving the output in correct order in bash debug mode. But it's not getting stored in the variable var.

Upvotes: 0

Views: 350

Answers (1)

KamilCuk
KamilCuk

Reputation: 142005

Why did the agent: no process killed is printing in the first line now?

I guess that is, because stdout is buffered, while stderr is not (or not so much). So stderr get's flushed after the line agent: no process killed is streamed while stdout is flushed after the script ./somescript.sh exists. So the first to show up on the screen is the first flushed stream - ie. stderr. While running in console, stderr and stdout both are set to be line buffed, int command substitution I guess bash set's stdout to be fully buffered.

How can I make it consistent to align both of them?

You can try setting line buffering in command substitution. var=$(stdbuf -oL -eL ./somescript.sh 2>&1)

Upvotes: 7

Related Questions