Making curl send errors to stderr and everything else to stdout

﹥>﹥吖頭↗ 提交于 2019-11-28 11:53:43
dgo.a

Try this:

# No error messages because it succeeds.
curl  http://www.shikadi.net/        --fail --silent --show-error

# This prints an error message to stderr
curl  http://i.like.you.def.maybe/   --fail --silent --show-error

Thanks to Russell Davis's answer on this page, man curl, and trial and error. For the curious, here is the wget version of the question: https://superuser.com/questions/420120/wget-is-silent-but-it-displays-error-messages

curl -s -S

From the man page:

-s Silent or quiet mode. Don't show progress meter or error messages. Makes Curl mute.

-S When used with -s it makes curl show an error message if it fails.

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

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 -f. The documentation says "Fail silently (no output at all) on server errors" but it really means "no output to stdout" -- errors will still be output to stderr.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!