Making curl send errors to stderr and everything else to stdout

前端 未结 4 2061
迷失自我
迷失自我 2020-12-10 00:20

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

The reason is that I am using curl from the command line (actually a cronjob)

4条回答
  •  隐瞒了意图╮
    2020-12-10 01:09

    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"
    

提交回复
热议问题