0

I have run into something interesting. As the title says, I am trying to redirect stderr to stdout and suppress/throw stdout. Before you flag this post as a duplicate (Shell: redirect stdout to /dev/null and stderr to stdout, or How to pipe stderr, and not stdout?, or IO Redirection - Swapping stdout and stderr) please give me a chance.

So, I want something like this:

#!/bin/bash

temp_func () {
    GLOBALVAR="$($1 "$2" 2>&1 >/dev/null)"
}

temp_func "echo" "hello world"
echo "should be empty: $GLOBALVAR"

temp_func "ecsdfho" "hello world"
echo "should show err: $GLOBALVAR"

The above works, as expected. Very cool.

If I now instead do:

PUSH_RESULT="$(git push "$REMOTE" "$NEW_TAG" 2>&1 >/dev/null)"

$PUSH_RESULT ends up being populated with an error when an error occurs (which is great) but also ends up containing git output upon a successful push. Why!?

NOTE: I was able to bypass this problem by doing something like:

PUSH_RESULT="$(git push -q "$REMOTE" "$NEW_TAG" 2>&1)"

but am curious why the initial method doesn't work.

Thank you.

Perplexabot
  • 1,852
  • 3
  • 19
  • 22

1 Answers1

1

ends up containing git output upon a successful push. Why!?

Because these messages are written to stderr as well. It's not just for errors, but also for progress and status messages that aren't considered an end product.

that other guy
  • 116,971
  • 11
  • 170
  • 194
  • Thank you! Is that considered bad practice (as in to use stderr for "none error" messages)? – Perplexabot May 24 '19 at 18:27
  • 1
    No, writing non-error status messages to stderr is a very good practice. Imagine if you couldn't do `curl http://example.com > file` because `curl` wrote connection info and a progress bar to the same stream as the downloaded file. – that other guy May 24 '19 at 18:33