Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

tee command not working as expected (with read and echo)

Tags:

linux

bash

unix

Script and output is as below :

Script :

#!/bin/bash
#tee_with_read.sh
function tee_test()
{
    echo "***This should be printed first but it is not***"
    read -r -p "Enter input : "
    echo "You entered : $REPLY"
}
tee_test | tee -a logfile

Output :

$ ./tee_with_read.sh
Enter input : ***This should be printed first, but it is not***
"My Input"
You entered : "My Input"

I'm trying to append output to logfile. But as you can see in ouput, it seems like first read gets excuted and then echo which is not as expected.

I'm using Git Bash Version 3.1.23 on windows 10. Since named pipe is not available in this version, I cannot use named pipe for logging purpose.

like image 339
San Avatar asked May 02 '16 16:05

San


1 Answers

read -p is writing it's output to stderr and echo is writing to stdout. stdout is typically buffered while stderr is not, and so it's not uncommon to see stderr things show up before stdout.

You could have your echo also go to stderr if you like by doing echo "string" >&2 or you could run it in the unbuffer command or similar tools if you have them available

like image 151
Eric Renouf Avatar answered Sep 30 '22 17:09

Eric Renouf