如何在 bash 脚本中检查空的 cherry-picks?

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

我有一个 bash 脚本,它 运行 遵循 cherry-pick 命令:

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

我再次尝试 运行ning 命令并在字符串中获取输出,然后比较字符串,但输出不是我在控制台中看到的。我正在使用以下脚本进行测试:

#!/bin/bash

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

echo $READ_STATUS

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

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

exit

下面是我在 运行 这个脚本时收到的输出:

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

所以我有两个问题:

  1. 为什么我的字符串没有得到完整的输出?
  2. 如何解决这个问题并成功检查 cherry-pick 是否导致空提交?

git 将其错误消息发送到 stderr,而不是 stdout。 READ_STATUS=$(git cherry-pick -x 001e6beda) 捕获标准输出并在 git 失败时将 READ_STATUS 设置为空。

您可以这样重写代码:

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

另请参阅:

  • String contains in Bash