1

I have the following simple example of which I don't understand how it comes to the output:

#!/bin/bash

function wtf() {
    echo -e "test1" >&1
    sleep 2
    echo -e "test2" >&1
}

a=$(wtf)
echo $a

The output on the terminal is AFTER 2 seconds test1 test2

When I change the last two lines just to wtf then the output is

 test1
 test2 #after 2 seconds
  1. Why is in the first version the test1 test2 in the same line?
  2. Why does the output of the line test1 test2 need 2 seconds to show up since only the second test2 should show up after 2 seconds?
0

1 Answer 1

2

The $(...) captures the stdout of the commands inside the subshell. The echo -e statements are not printed to the stdout of the calling shell, but get buffered in the subshell. If you remove the echo $a command then nothing will be printed at all.

The subshell in this example doesn't exit until wtf completes. That's why you have to wait 2 seconds, so that the calling shell gets back control, and does echo $a, printing all the output that was captured by the subshell.

Sign up to request clarification or add additional context in comments.

2 Comments

Thx for the clarification, is there a way to print to the stdout anyways in the function?
stdout will be captured by the subshell, so no, you cannot. You could print to stderr though, with echo test3 >&2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.