3

I have a list of git commits in a .txt file and I want to iterate over the commits. For each COMMIT_ID I want check them using a git command whose exit code is 0 or 1.

Depending on the result I want to echo true or false.

But when running the script, I get this error:

line 5: [: 0: unary operator expected

The script is as follows:

#!/usr/bin/env bash
input="./commits.txt"
while IFS= read -r COMMIT_ID
do
  if [ 0 -eq $(git merge-base --is-ancestor $COMMIT_ID HEAD) ]; 
    then 
      echo "true"; 
    else 
      echo "false"; 
    fi
done < "$input"
Stephen Kitt
  • 411,918
  • 54
  • 1,065
  • 1,164

1 Answers1

7

$() is replaced with the output of the given command, not its exit code. To use an exit code, use the command directly with if:

if git merge-base --is-ancestor "$COMMIT_ID" HEAD; then
Jeff Schaller
  • 66,199
  • 35
  • 114
  • 250
Stephen Kitt
  • 411,918
  • 54
  • 1,065
  • 1,164
  • To clarify a little bit: Output as in what's printed to *standard output*. For example, `echo hello $(echo world >&2) goodbye` will print `world`, then `hello goodbye` -- standard error still gets printed, instead of being captured. – Nic Jun 27 '19 at 21:39