Bash Command To Go Back To Previous Directory

If you are using the bash shell on your Linux or macOS system and want to get back to the previous directory form the current directory you are in, you can make use of the cd change directory command followed by double dots ..


Example:

bash-3.2$ pwd
/Users/c2ctech/Desktop

bash-3.2$ cd ..
bash-3.2$ pwd
/Users/c2ctech

bash-3.2$ cd ..
bash-3.2$ pwd
/Users

bash-3.2$ cd ..
bash-3.2$ pwd
/
bash-3.2$ 

As you can see in the above example, using pwd command, I have displayed the current location and then made use of the cd .. to move to the previous directory until I reached to the root directory.

bash command to move to previous directory example

Note that there is a space between cd and the .. , if you do not add a space you will get an error bash: cd..: command not found

$  cd..
bash: cd..: command not found

If your requirement is to go back to the previous directory and not a step back, then you can make use of the $OLDPWD environment variable.

Let's take a look at an example.

    Say your current location is /usr/bin

    bash-3.2$ pwd
    /usr/bin

    Now say you move to /Applications/XAMPP/htdocs.

    bash-3.2$ cd /Applications/XAMPP/htdocs

    Now if you run a few commands,

    bash-3.2$ who
    c2ctechtv        console      Aug 12 08:44 
    c2ctechtv        ttys000      Aug 14 10:09 
    c2ctechtv        ttys001      Aug 14 10:10 
    bash-3.2$ whoiam
    bash: whoiam: command not found

    At this moment, if you want to go back to the previous directory location, just make use of cd "$OLDPWD"

    bash-3.2$ cd "$OLDPWD"
    
    bash-3.2$ pwd
    /usr/bin

    Comments & Discussion

    Facing issues? Have questions? Post them here! We're happy to help!