Search code examples
gitbashcherry-pickgit-cherry-pick

How to check for empty cherry-picks in a bash script?


I have a bash script which runs following cherry-pick command:

if git cherry-pick -x "$commitId"; then
        ammed_commit "$BRANCH" 
  else
      #here I want to check if this resulted in empty commit
fi

I tried running the command again and getting output in a string and then compare the string, but the output is not what I see in console. I am testing with the following script:

#!/bin/bash

READ_STATUS=$(git cherry-pick -x 001e6beda)
SUB_STRING="The previous cherry-pick is now empty"

echo $READ_STATUS

stringContain() { [ -z "${2##*$1*}" ]; }

if stringContain "$READ_STATUS" 'The previous cherry-pick is now empty';then 
  echo yes
else 
  echo no
fi

exit

Below is the output I receive when I run this script:

The previous cherry-pick is now empty, possibly due to conflict resolution.
If you wish to commit it anyway, use:

git commit --allow-empty

Otherwise, please use 'git reset'
//READ_STATUS gets this value and not the one above this line???
On branch test-stage Your branch is ahead of 'upstream/test-stage' by 1 commit. (use "git push" to publish your local commits) You are currently cherry-picking commit 001e6beda. nothing to commit, working tree clean
no

So I have got two questions:

  1. Why my string is not getting the complete output?
  2. How can I resolve this and successfully check if cherry-pick results in an empty commit?

Solution

  • The git sends its error messages to stderr, not stdout. READ_STATUS=$(git cherry-pick -x 001e6beda) captures the stdout and sets READ_STATUS to nothing when git fails.

    You can rewrite your code this way:

    read_status=$(git cherry-pick -x 001e6beda 2>&1)
    empty_message="The previous cherry-pick is now empty"
    if [[ $read_status = *"$empty_message"* ]]; then
      echo yes
    else
      echo no
    fi
    

    See also: