Reputation: 3335
I have this bash script that I want to duplicate a branch and make a PR to a remote repo using that duplicate branch then delete the duplicate branch:
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:$1
fi
git checkout $branch
git branch -D $prBranch
}
The problem is the variable branch
gets re evaluated to what prBranch
is pointing to by the time
git checkout $branch
When this code runs, the branch
variable is the new branches name instead of the first value from the first line of code.
Any thoughts on how to preserve the value of branch for later execution of the bash script?
edit
gp () {
branch=$(git rev-parse --abbrev-ref HEAD)
git push origin $branch
}
this was previously not present in the original prompt, but is the reason for the bug.
Upvotes: 0
Views: 433
Reputation: 295629
This quite certainly means your bp
function starts like:
bp() {
branch=$1
othervar=$(whatever)
# ...do stuff here...
}
You can't do that safely, because -- like Javascript -- variables are global by default in bash. Thus, setting branch
inside a function you call changes the value in the parent as well.
Always declare your locals, like so:
bp() {
local branch othervar
branch=$1
othervar=$(whatever)
# ...do stuff here...
}
(Why two separate lines, rather than local branch=$1
? Because when you want to move on to local foo=$(bar)
, the local
command eats the exit status of bar
, making its success or failure impossible to determine later; maintaining a habit of keeping your local declarations to a separate line avoids the issue).
Upvotes: 1