16

Super noob question: I can navigate down in directory using cd from the terminal. How do I navigate back up if I go too far?

30

cd .. will bring you back exactly one directory up.

You can string together those to go up multiple directories, e.g. up 3

cd ../../..

Instead of typing cd .. multiple times, what you could to is to place the function bellow into your .bashrc somewhere at the top, save .bashrc, and run source .bashrc or just close and reopen a terminal. Now, you have a function that does cd.. exactly how many times you told it to.

function goUp {
  num=$1
  while [ $num -ne 0  ];do
    cd ..
    num=$((num-1))
  done
}

Demo:

$ cd /usr/share/backgrounds/                                                  

backgrounds:$ goUp 2

usr:$ 

Alternatively:

goup(){ 
    cd $(n=$1 awk 'BEGIN{
        for(i=1;i<=ENVIRON["n"];i++) 
            printf "../"}';) 
}

Note that such method brings you back along the symlinks. Here's what I mean:

$ namei "$PWD" 
f: /home/user/VirtualBox VMs/CentOS
 d /
 d home
 d user
 l VirtualBox VMs -> /mnt/ubuntu/vboxvms
   d /
   d mnt
   d ubuntu
   d vboxvms
 d CentOS

$ goup 2
$ pwd
/home/user

See also

  • Added some more info, check it. – Sergiy Kolodyazhnyy Nov 28 '15 at 23:36
  • That could be just for i in $(seq "$1"); do cd ..; done. – deltab Nov 29 '15 at 2:08
  • @deltab true, could be done as well . . . .But I prefer using while + counter to simulate a for loop. I've asked a relevant question before on U&L site – Sergiy Kolodyazhnyy Nov 29 '15 at 2:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.