Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

With bash is there a way to push and pop the current working directory? I tried writing bash;cd dir; ./dostuff;exit; but the current directory is now dir.

share|improve this question
up vote 40 down vote accepted

There is pushd and popd

Bash will keep a history of the directories you visit, you just have to ask. Bash stores the history in a stack and uses the commands pushd and popd to manage the stack.

More to read

Example:

$ pwd; pushd /tmp; pwd; popd; pwd
/home/me
/tmp ~
/tmp
~
/home/me
share|improve this answer

Calling bash starts a new subshell, which has its own input; none of the other commands will run until it exits. Surrounding the commands to be run with parens will also start a new subshell, but it will run the commands within it.

( cd dir ; ./dostuff )
share|improve this answer

If you don't need multiple levels of directory history, you can also do:

cd foo
# do your stuff in foo
cd -

Compared to pushd/popd, this has the disadvantage that if cd foo fails, you end up in the wrong directory with cd -.

(Probably cd - is more handy outside scripts. "Let's go back where I just was.")

share|improve this answer

I use alias for keeping track of my directory changes so to 'cd' somewhere I can just go back to where I was using 'cd.', or go back two using 'cd..', etc.;

alias pushdd="pushd \$PWD > /dev/null"
alias cd='pushdd;cd'
alias ssh='ssh -A'
alias soc='source ~/.bashrc'
#below to go back to a previous directory (or more)
alias popdd='popd >/dev/null'
alias cd.='popdd'
alias cd..='popdd;popdd'
alias cd...='popdd;popdd;popdd'
alias cd....='popdd;popdd;popdd;popdd'
#below to remove directories from the stack only (do not 'cd' anywhere)
alias .cd='popd -n +0'
alias ..cd='popd -n +0;popd -n +0;popd -n +0;popd -n +0;popd -n +0;popd -n +0;popd -n +0;popd -n +0;popd -n +0;popd -n +0'
share|improve this answer
    
Can you explain in more detail what this code does? – bwDraco Feb 17 '15 at 17:31

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .