无法在 git 中弹出命名存储

can't pop named stash in git

我正在尝试编写一组 bash 命令,这些命令将:

  1. 存储当前更改
  2. 签出并拉取 SOURCE 分支
  3. 签出并拉取 TARGET 分支
  4. 将 TARGET 分支与 SOURCE 分支合并
  5. 将更改推送到 TARGET 分支
  6. 签出初始分支
  7. 从存储中弹出更改

首先,我不知道这是否是使用 bash 脚本合并两个分支的正确方法。
问题是我在存储和取消存储命名存储时遇到困难。这是我的脚本:

while getopts "s:t:" option; do
    case "${option}" in
        s) SOURCE=${OPTARG};;
        t) TARGET=${OPTARG};;
    esac
done

if [ "${SOURCE}" = "" ]; then
    echo "SOURCE argument is missing"
    exit 1
fi

if [ "${TARGET}" = "" ]; then
    echo "TARGET argument is missing"
    exit 1
fi

CURRENT_BRANCH=$(git rev-parse --abbrev-ref HEAD)

echo "Stash changes..."
git stash save GIT_DEPLOY_STASH

echo "Checkout and pull ${SOURCE}..."
git checkout ${SOURCE}
git pull --rebase origin ${SOURCE}

echo "Checkout and pull ${TARGET}..."
git checkout ${TARGET}
git pull --rebase origin ${TARGET}

echo "Merge and push ${SOURCE}..."
git merge ${SOURCE}
git push origin ${TARGET}

echo "Checkout ${CURRENT_BRANCH}..."
git checkout ${CURRENT_BRANCH}

echo "Pop stash..."
git stash pop stash^{/GIT_DEPLOY_STASH} #<--- THIS ISN'T WORK!

用法示例:

$ sh ./my-script.sh -s develop -t staging

知道如何解决命名存储问题吗? 知道如何改进此脚本吗?

git stash pop不允许regexp revision selection喜欢stash^{/GIT_DEPLOY_STASH}

来自git stash documentation:

When no <stash> is given, stash@{0} is assumed, otherwise must be a reference of the form stash@{<revision>}.

但是你可以使用git stash apply

Unlike pop, <stash> may be any commit that looks like a commit created by stash save or stash create.

但是由于您在脚本中使用它,因此您应该使用 git stash create,因为它只会创建提交。

Create a stash (which is a regular commit object) and return its object name, without storing it anywhere in the ref namespace. This is intended to be useful for scripts. It is probably not the command you want to use; see "save" above.

所以用这种方式改变你的脚本

echo "Stash changes..."
GIT_DEPLOY_STASH=$(git stash create 2>/dev/null)

if [ -z ${GIT_DEPLOY_STASH}" ] ; then
    echo "Nothing to stash..."
else
    # echo the stash commit. Useful if your script terminates unexpectedly
    echo "GIT_DEPLOY_STASH created ${GIT_DEPLOY_STASH} ..."
fi


# RESET THE WORKING DIR, BECAUSE STASH CREATE ONLY CREATES THE STASH COMMIT
git reset --hard

...

if [ -n "${GIT_DEPLOY_STASH}" ] ; then
   git stash apply ${GIT_DEPLOY_STASH}
fi