Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

bash - Stop git from writing non-errors to stderr

I have a script that I am using to automatically sync various remote git repositories. One thing I am trying to do with my scripts is to capture the output of stderr from every command and write all those errors into a text file that is then emailed to me after the script has finished. This will alert me to any problems that I need to fix. I am having a problem with the following two lines though:

{
    git fetch --prune-tags github-fetch master
    git push github master 
} 2> '/tmp/stderr-contents-sync_git_repositories.txt'

The problem is that the git fetch line is writing the following to stderr:

From https://github.com/XJDHDR/xjdhdr-random-code.wiki
 * branch            master     -> FETCH_HEAD
   13af304..333d602  master     -> github/master

and the git pull line is writing this:

To ssh://github.com/XJDHDR/xjdhdr-random-code.wiki.git
   333d602..da65970  master -> master

My problem is that neither of these are errors and they are emailed every time I run the script. I would like to know if it is possible to either stop git from writing these non-errors to stderr or filter these sort of messages out of the stderr output while preserving genuine errors.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

write all those errors into a text file

Those are not always error, considering most Git commands outputs information message on stderr, as I mentioned here:

stderr as it is just informative messages, not to be consumed by machines.

If it better to test the exit status of the command and email both stdout and stderr if said exit status differs from 0

Plus, you are doing two redirections: > followed by >: the second one would recreate /tmp/stderr-contents-sync_git_repositories.txt: that second redirection should be >>, not >.

So:

git fetch --prune-tags github-fetch master > tmp 2>&1 || cat tmp > '/tmp/stderr-contents-sync_git_repositories.txt'
git push github master > tmp 2>&1 || cat tmp >> '/tmp/stderr-contents-sync_git_repositories.txt'

Here I override a tmp file on each command (with their stdout/stderr), and if that command fails, I write to, or I append to /tmp/stderr-contents-sync_git_repositories.txt.

This is easier than your edit, where you redirect both commands to a file, even if one of them might have failed.

That is why I do cmd1 || cat >> file: the >> part only runs if cmd1 fails.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...