0

I have a variable in bash:

branchName=$(git branch --show-current)

There are two options for the returned value:

  • banch name (e.g. master)
  • fatal: not a git repository (or any of the parent directories): .git

I want to check if branchName starts with fatal:

I have tried to check if it starts with master and it works:

if [[ $branchName == master* ]];
    then echo "yes"
fi
echo $branchName
Output:
yes
master

but when I try to check if it starts with fatal: it does not work:

if [[ $branchName == fatal* ]];
    then echo "yes"
fi
Output:
fatal: not a git repository (or any of the parent directories): .git

1 Answers1

0

but when I try to check if it starts with fatal: it does not work:

It's because this is an error message and goes to stderr. What you capture is only the stdout.

A better approach is to check the return value instead. E.g.

if branchName=$(git branch --show-current 2>/dev/null); then
    echo "Branch is: $branchName"
else
    echo "Error: can't get branch name"
fi

(If command succeeds, it'd return 0; any non-zero value is usually treated as failure. The if statement above would be "true" when git return 0).

But if you do want to capture stderr, you can do:

branchName=$(git branch --show-current 2>&1)
P.P
  • 117,907
  • 20
  • 175
  • 238
  • 1
    You want `if branchName=$(git ...); then`; see https://stackoverflow.com/questions/36313216/why-is-testing-to-see-if-a-command-succeeded-or-not-an-anti-pattern – tripleee Aug 08 '20 at 09:37