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
416 views
in Technique[技术] by (71.8m points)

stdout - Bash redirecting synchronization dilemma

In order to automate some system update functionality I have written some BASH scripts.

What I want to achieve is to redirect stdout and stderr to a log file and stderr to the terminal running the script.

This is what I have come up with so far: ((./cmd >logfile) 2>&1) | tee logfile

Note ./cmd is a placeholder here, in my script it is actually an ssh call into one of my machines.

The unfortunate thing is that writing to the same file from two different processes is not ideal. My update.log obviously shows signs of the two writes stomping on each other. I want the log to interleave so the errors thrown are close to the relevant standard output, thus writing to separate files and merging them afterwards is not really an option.

Any suggestions would be greatly appreciated.


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

1 Reply

0 votes
by (71.8m points)

Have tee copy its stdin to the controlling terminal, pipe ./cmd's stderr to tee's stdin, and redirect both programs' stdout to a file descriptor connected to logfile. tee does not buffer its output, so make sure ./cmd doesn't either, and hope for the best.

{ stdbuf -o 0 ./cmd 2>&1 >&3 | tee /dev/tty >&3; } 3>logfile

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

...