obayhan
obayhan

Reputation: 1732

How to check if git has differences between 2 branch in a bash script

I need to check in a bash script if there is differences between 2 branch in a git repository. I know it is possible to see differences with git diff. However i need to use it in if.

how can i do that?

For example:

git diff ......
if [ $? -eq 1 ] 
then
    echo "will do something in here"
fi

Upvotes: 3

Views: 1139

Answers (2)

tjm3772
tjm3772

Reputation: 3219

(edit: swapped --exit-code for --quiet which suppresses output)

git diff --quiet will cause the command to set an exit code similar to the normal diff command if there are differences.

if ! git diff --quiet <commit1> <commit2> ; then
  echo "Different"
else
  echo "Not different"
fi

If you care about inspecting the specific error code:

git diff --quiet <commit1> <commit2>
case $? in
  0) echo "Not different" ;;
  1) echo "Different" ;;
  128) echo "Invalid commit id(s)" ;;
  *) echo "Unknown error" ;;
esac

Upvotes: 10

Skwll
Skwll

Reputation: 21

Here's an example:

#!/bin/bash

# Set the branch names
BRANCH1="master"
BRANCH2="my-feature-branch"

# Check if there are differences between the two branches
DIFFERENCES=$(git diff --name-only $BRANCH1 $BRANCH2)

# If there are differences, print a message
if [ -n "$DIFFERENCES" ]; then
  echo "There are differences between the $BRANCH1 and $BRANCH2 branches."
else
  echo "There are no differences between the $BRANCH1 and $BRANCH2 branches."
fi

Upvotes: 2

Related Questions