使curl将错误发送到stderr,将其他所有错误发送到stdout [英] Making curl send errors to stderr and everything else to stdout

查看:205
本文介绍了使curl将错误发送到stderr,将其他所有错误发送到stdout的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法告诉curl将错误输出到stderr,并将其他所有结果告诉stdout?

Is there a way to tell curl to output errors to stderr, and everything else to stdout?

原因是我在命令行中使用curl(实际上是一个cronjob)每天晚上将文件上传到FTP站点。不幸的是,因为curl在stderr上输出了状态信息,所以当实际上没有发生任何错误时,我会收到一封有关错误的电子邮件。 (我将stdout重定向到日志文件,但保持stderr不变,以便cron如果有任何输出将通过电子邮件将其发送给我。)

The reason is that I am using curl from the command line (actually a cronjob) to upload a file to an FTP site every evening. Unfortunately because curl outputs status information on stderr, I receive an e-mail about an error when nothing actually went wrong. (I'm redirecting stdout to a log file, but leaving stderr unchanged so that cron will e-mail it to me if there is any output.)

有选项可以使curl保持静默状态或将所有内容输出到stdout,但是这两种选择都可以防止在stderr上出现错误-这意味着当我确实想知道一个错误时,我不会收到电子邮件。

There are options to make curl silent, or output everything to stdout, however both these alternatives prevent errors from appearing on stderr - meaning I won't get an e-mail when there is actually an error I want to know about.

有没有办法使stderr上的curl只发生输出错误,而在stdout上保持正常输出呢?

So is there a way to make curl only output errors on stderr, but leave normal output intact on stdout?

推荐答案

经过更多的实验后,我想出了以下解决方法,但是我仍然对更好的选择持开放态度。

After some more experimentation I have come up with the following workaround, but I'm still open to better alternatives.

它可以通过临时存储所有内容来工作在临时文件中输出(stdout和stderr),然后根据curl的退出代码将该文件的内容发送到stderr或stdout。如果curl失败,则整个输出将发送到stderr(并通过cron发送给我,以电子邮件形式发送给我),但是如果curl成功,则输出将转到stdout(在cron命令中重定向到日志文件,从而导致没有电子邮件。)

It works by temporarily storing all output (stdout and stderr) in a temporary file, and then sending the contents of that file to stderr or stdout depending on curl's exit code. If curl failed the entire output will go to stderr (and be e-mailed to me thanks to cron), but if curl succeeded the output will go to stdout instead (which is redirected to a log file in the cron command, resulting in no e-mail.)


# Get a temporary filename
CURL_LOG=`tempfile`

(
  # Run curl, and stick all output in the temp file
  /usr/bin/curl --verbose ... > "$CURL_LOG" 2>&1
) || (
  # If curl exited with a non-zero error code, send its output to stderr so that
  # cron will e-mail it.
  cat "$CURL_LOG" > /dev/stderr
  rm "$CURL_LOG"
  exit 1
)

# Otherwise curl completed successfully, so send the output to stdout (which
# is redirected to a log file in crontab)
cat "$CURL_LOG"
rm "$CURL_LOG"

这篇关于使curl将错误发送到stderr,将其他所有错误发送到stdout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆