Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
349 views
in Technique[技术] by (71.8m points)

bash - Prepend timestamp to every output line of a command

I have this script that should prepend the timestamp to every output line of a command:

  $command 2>&1 | while IFS= read -r line; do printf '[%s] %s
' "$(date '+%Y-%m-%d %H:%M:%S')" "$line"; done 

It's working fine for most cases, but I have a certain case in which I have an issue.

Let's take for example this:

read -rep "Your age: " age | while IFS= read -r line; do printf '[%s] %s
' "$(date '+%Y-%m-%d %H:%M:%S')" "$line"; done

In this case the timestamp is not prepended.

I understand the problem here is that the newline is not reached so the newline is not printed. I was wondering if is possible to print all the chars as they are received and then print the timestamp once we get a newline.

question from:https://stackoverflow.com/questions/65922422/prepend-timestamp-to-every-output-line-of-a-command

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The issue here is that the read command is not writing anything to stout and so the while loop has no output to process and loop on. By adding an echo of the age, you get the required result.

read -rep "Your age: " age;
echo $age | while IFS= read -r line; 
do 
  printf '[%s] %s
' "$(date '+%Y-%m-%d %H:%M:%S')"; 
done

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...