I am trying to register a script alias in my .bashrc
for easy switching from the current branch to master, pulling, switching back to the branch, and rebasing.
Currently, my alias script looks like this:
alias gmm="branch=$(git rev-parse --abbrev-ref HEAD);
echo \"Switching from '$branch' to 'master'\";
git checkout master;
git pull;
echo \"Switching from 'master' to '$branch'\";
git checkout $branch;
git rebase master"
However, the current branch does not seem to be saved to the branch
variable, and the command prints the following:
Mai@DESKTOP-M71G3R MINGW64 /c/dev/git/myrepo (testing)
$ gmm
Switching from '' to 'master'
Switched to branch 'master'
Your branch is up to date with 'origin/master'.
Authorized uses only. All activity may be monitored and reported
Already up to date.
Switching from 'master' to ''
Your branch is up to date with 'origin/master'.
Successfully rebased and updated refs/heads/master.
I have already checked that the command itself indeed gets the current branch name:
Mai@DESKTOP-M71G3R MINGW64 /c/dev/git/myrepo (testing)
$ branch=$(git rev-parse --abbrev-ref HEAD)
Mai@DESKTOP-M71G3R MINGW64 /c/dev/git/myrepo (testing)
$ echo $branch
testing
I've spent days googling but I can't figure out where and why the variable assignment fails.
CodePudding user response:
You should use single quotes for alias content as suggested here. When using double quotes, $(git rev-parse --abbrev-ref HEAD)
will resolve as early as .bashrc
is executed and will probably become empty string. If you use single quotes instead, $(git rev-parse...)
will resolve when gmm
is run, which means it correctly becomes current branch's name.
alias gmm='branch=$(git rev-parse --abbrev-ref HEAD);
echo "Switching from '\''$branch'\'' to master";
git checkout master;
git pull;
echo "Switching from master to '\''$branch'\'';
git checkout "$branch";
git rebase master'
Preferably I would use bash function instead of alias, which is more convenient.
gmm() {
local branch=$(git rev-parse --abbrev-ref HEAD);
echo "Switching from $branch to master";
git checkout master;
git pull;
echo "Switching from master to $branch";
git checkout "$branch";
git rebase master
}