bash 保持变量的旧值

bash maintain old value for variable

我有这个 bash 脚本,我想复制一个分支并使用该复制分支对远程仓库进行 PR,然后删除复制分支:

gPullRequest () {
  branch=$(git rev-parse --abbrev-ref HEAD)
  if [ $# -eq 0 ]
    then
      git checkout -b development-$branch
  elif [ $# -eq 1 ]
    then
      git checkout -b release-$branch
  fi
  gp
  prBranch=$(git rev-parse --abbrev-ref HEAD)
  if [ $# -eq 0 ]
    then
      hub pull-request -h org:$prBranch -b org:development
  elif [ $# -eq 1 ]
    then
      hub pull-request -h org:$prBranch -b org:
  fi
  git checkout $branch
  git branch -D $prBranch
}

问题是变量 branch

时被重新评估为 prBranch 指向的内容
git checkout $branch

当此代码运行时,branch 变量是新的分支名称,而不是第一行代码中的第一个值。

关于如何保留 branch 的值以便以后执行 bash 脚本有什么想法吗?

编辑

gp () {
  branch=$(git rev-parse --abbrev-ref HEAD)
  git push origin $branch
}

这在以前的原始提示中不存在,但却是错误的原因。

这肯定意味着您的 bp 函数开头如下:

bp() {
  branch=
  othervar=$(whatever)
  # ...do stuff here...
}

你不能安全地这样做,因为 - 就像 Javascript - 变量在 bash 中默认是全局的。因此,在您调用的函数中设置 branch 也会更改父项中的值。

总是像这样声明你的本地人:

bp() {
  local branch othervar
  branch=
  othervar=$(whatever)
  # ...do stuff here...
}

(为什么分两行,而不是 local branch=?因为当你想转到 local foo=$(bar) 时,local 命令吃掉了退出状态bar,使得以后无法确定其成功或失败;保持将本地声明保持在单独一行的习惯可以避免该问题。