Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Git pushd & popd? I.e., checkout last state

I'm writing a Bash script, and I want to checkout a tag and then checkout back to where I started.

I tried git co HEAD@{1}, but when starting at master, that takes me back to the commit SHA of master but with a detatched head.

Is there something like pushd & popd for Git?

like image 876
ma11hew28 Avatar asked Mar 01 '11 05:03

ma11hew28


People also ask

What is pushd in git?

The git push command is used to upload local repository content to a remote repository. Pushing is how you transfer commits from your local repository to a remote repo. It's the counterpart to git fetch , but whereas fetching imports commits to local branches, pushing exports commits to remote branches.

What is the pushd command?

The pushd command is used to save the current directory into a stack and move to a new directory. Furthermore, popd can be used to return back to the previous directory that is on top of the stack. It is very useful when we have to switch between two directories frequently.

What is the purpose of pushd and popd?

Pushd and popd are the fastest navigational commands you've never heard of. The pushd and popd commands are built-in features of the Bash shell to help you "bookmark" directories for quick navigation between locations on your hard drive.

Does pushd create directory?

pushd adds a directory to the top of the stack and popd removes a directory from the top of the stack. To display directories in the directory stack (or history), we can use the dirs command as shown.


2 Answers

git checkout @{-1} which can be abbreviated to git checkout -.

From the manpage:

As a special case, the "@{-N}" syntax for the N-th last branch checks out the branch (instead of detaching). You may also specify - which is synonymous with "@{-1}".

like image 91
wnoise Avatar answered Sep 22 '22 15:09

wnoise


EDIT: wnoise's suggestion will work if you don't want to keep an explicit history the way pushd/popd does. If you do (and don't want an ordinary checkout to affect your LRU):

I don't know of anything that will do what you want out of the box, but it's not to hard to hack together something along those lines. If you add a file named git-foo to your PATH, you get a new git foo command. So, git-pushd could look like:

#!/bin/bash

SUBDIRECTORY_OK=1
. $(git --exec-path)/git-sh-setup

git symbolic-ref HEAD | sed s_refs/heads/__ >> $GIT_DIR/.pushd
git checkout "$@"

And git-popd:

#!/bin/bash

SUBDIRECTORY_OK=1
. $(git --exec-path)/git-sh-setup

REF=$(head -n1 $GIT_DIR/.pushd)

[ -n "$REF" ] || die "No refs to pop"
git checkout "$REF" && sed -i -e '1d' $GIT_DIR/.pushd
like image 35
Walter Mundt Avatar answered Sep 25 '22 15:09

Walter Mundt