Search code examples
linuxcd

Why does "cd -" behave as it does?


What does cd - exactly do ? ( the change directory command, plus a dash )

I noticed that if I run it in my /home/user folder repeatedly it outputs either /home/user or /home, this changes if I run it from a different folder.


Solution

  • cd - 
    

    pop the last directory you were from the stack of directory. It's like hitting "back" on the browser.

    Exemple :

    you are in /user/alex

    you can test that with : pwd that give you /user/alex

    then if you do

    %cd project1/subfolder
    %pwd 
    /user/alex/project1/subfolder
    %cd subsubfolder
    %pwd
    /user/alex/project1/subfolder/subsubfolder
    %cd - 
    pwd 
    /user/alex/project1/subfolder
    cd - 
    pwd 
    /user/alex
    

    NB : it's not going back a level upper in the folder hierarchy. it's going to the previous current folder. ( a level upper is cd .. ).