90

Is there any way to jump back to the previous working directory after doing a cd to a different directory?

My use-case is that I'm traversing a directory structure for a Java project, and I'm expecting that the current directory has only one sub-directory. So, I type cd and hit Tab and Enter rather quickly. However, the Tab failed, as I mistakenly expected one sub-directory, when in fact there are more. So now, I just executed cd, and am now in my home directory, instead of the Java project. Is there a way to "undo" this cd and jump back to the directory I was in?

5 Answers 5

149

You can use cd - to go back to your previous location, no matter where that was.

0
22

cd - is great for going back one level, but if you find yourself wanting to go back a few levels, check out this script:

acd_func.sh

It's great. cd -- to see your history, and cd -3 to go back 3 levels, for example.

2
  • Wow... a geocities link. Now there's a URL I have not seen in a long time. <insert Obi-wan JPG> Jun 1, 2015 at 14:07
  • 1
    the gist of this comment. <jpg Yoda insert>
    – Donbhupi
    Oct 17, 2015 at 6:59
18

You can also use pushd and popd to utilize the directory stack. Here's some information.

6

In addition, cd .. can take you back to the working directory's parent directory and then if necessary the command can be repeated until you get to where you want to be. In fact, each time it is evoked it takes you back through the directory tree, which would ultimately finish at / (the root directory) if you just kept repeating the command.

In contrast, cd - actually makes the previous working directory the current working directory, (which is known as .), and which exact location in the filesystem can be found with pwd.

So both cd .. and cd - can be useful in different circumstances when navigating the directory tree, although they do differ in the aforementioned respects. Perhaps the most useful command after having fun experimenting with these two commands is cd, which returns you to the home folder.

-1

Best way to do this for going back is cd -, however if you want to skip a lot of levels at once, you better use cd .. for one level, cd ../.., for two, cd ../../.. for three and on... a nice way to do it fast is this script:

#!/bin/bash
printf "Number of folders to move back: "
read TIMES
BACKCHARS=../
BACK=$(for i in `seq $TIMES`; do printf $BACKCHARS; done)
cd $BACK
2
  • 1
    Running cd in a script doesn't affect the parent shell. You'd need to put this in a shell function for it to be useful.
    – wjandrea
    Apr 28, 2017 at 0:25
  • like this: up(){ local n="$1"; while ((n--)); do path+='../'; done; cd "$path"; }
    – wjandrea
    Apr 28, 2017 at 0:54

You must log in to answer this question.

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