0

I run git -C /another-directory pull and I get this error:

Your configuration specifies to merge with the ref 'refs/heads/main'
from the remote, but no such ref was fetched.

Now I want to get that response in a variable.

I tried read Result < <(git -C /another-directory pull) and then I ran echo $Result and it's empty.

I also tried git -C /another-directory pull | read Result and again, it's empty.

What can I do?

1 Answers1

3

That's output on standard error, not standard output.

To capture both stdout and stderr:

Result=$(git ... 2>&1)

To capture only stderr while discarding stdout:

Result=$(git ... 2>&1 > /dev/null)

To capture only stderr while leaving stdout alone:

{ Result=$(git ... 2>&1 >&3 3>&-); } 3>&1

read is the command to read words from one logical line (physical lines possibly continued using trailing backslashes).

To read one line into a variable, you use IFS= read -r line.

So here, to read the first line of the standard error of git, you could do:

IFS= read -r Result < <(git ... 2>&1 > /dev/null)

But that has several drawbacks:

  • you lose the exit status of git. That command will succeed if read succeed, that is if it manages to read one full line
  • as read will stop reading and exit after the first line, git's stderr will become a broken pipe so could end up being killed if it prints more errors.

To get only the first line while still not breaking git's stderr pipe and preserving its exit status, you could do:

Result=$(
  set -o pipefail
  git ... 2>&1 > /dev/null | sed '1!d'
)

Note that the syntax to print the contents of a variable is printf '%s\n' "$var, not echo $var. See also typeset -p var in Korn-like shells to print its definition.

  • I guess my mind is tired or locked to see this simple thing. I had the knowledge of stdout and stderr, but I could not use that knowledge here. Thank you so much. – Saeed Neamati Mar 13 '23 at 07:38