How to checkout a file from the current tracking branch?

59 Views Asked by At

We would like to checkout the current file from a the currently tracked remote branch. Currently we have:

git fetch && git checkout origin/main RoboFile.php

But we need to change this code for each branch. If we are currently on develop, we would need to call

git fetch && git checkout origin/develop RoboFile.php

instead.

Is there a straight forward way to unify this command?

1

There are 1 best solutions below

0
Romain Valeri On BEST ANSWER

The branch-agnostic way to refer to some local branch's remote counterpart is the [<branchName>]@{upstream} construct (@{u} in short form).

Just do

git fetch && git checkout @{u} -- RoboFile.php

Note : -- is not strictly necessary here, but it's a good practice to explicitly separate options and paths. (doc)


(Note in answer to above comments: git rev-parse is superfluous here, since @{u} already will be substituted with the ref it describes, namely the remote-tracking branch associated (for pull) with the (currently checked out if you omitted <branchName> since HEAD@{u} is then implied) local one.)