Skip to main content

Git tips and tricks

· 2 min read
Hreniuc Cristian-Alexandru

1. Rebase ony one(or X) commits from a brach over another branch:

One commit:

git rebase --onto origin/devel branch_name~1 branch_name

Multiple commits:

git rebase --onto origin/devel branch_name~4 branch_name

2. Add a git worktree:

git worktree add --track -b new_branch_name name_of_folder_to_be_created_for_worktree branch_to_start_from

Example:

git worktree add --track -b branch_1 project_1 master

3. Checkout a single file from a specific commit:

git checkout commit_or_branch file_path

4. Overwriting local branch with remote branch:

git checkout branch
git fetch --all
git reset --hard origin/branch

be careful, this will remove any changes from your working tree!


5. Merge two branches witout checking out on the branch that me want to merge:

I want to merge the chreniuc_548 into devel.

One way to do it is this, but this does a checkout:

git checkout devel
git merge chreniuc_548

Without checking out, you can do this:

# Merge local branch foo into local branch master,
# without having to checkout master first.
# Here `.` means to use the local repository as the "remote":
git fetch . chreniuc_548:devel

# Merge remote branch origin/foo into local branch foo,
# without having to checkout foo first:
git fetch origin foo:foo

Source: https://stackoverflow.com/a/17722977


6. Push current branch:

git config --global push.default current
# Afterwards:
git push

Source: https://stackoverflow.com/questions/14031970/git-push-current-branch-shortcut


7. Aliases:

$ git config --global alias.co checkout
$ git config --global alias.br branch
$ git config --global alias.ci commit
$ git config --global alias.st status

# Afterwards:

git st

Source: https://git-scm.com/book/en/v2/Git-Basics-Git-Aliases

Or, we can define them in .bashrc:

alias status='git status'
alias branch='git branch'
alias commit='git commit'
alias checkout='git checkout'
alias push='git push'
alias fetch='git fetch origin -p'
alias add='git add'
alias merge='git merge'