Moving up levels in directory tree easily

In Linux if you are in a directory level and want to jump for example 2-3 folders in one step, as far as I know there is no built-in command. If there is one, I would be very happy to know. There is a very nice command in Juniper’s JUNOS CLI which is “up” which moves you up in the configuration hierarchy. I wanted to do the same via a bash script like below;

#!/bin/bash
# The script which moves you level up provided by
# the first argument in the directory tree

dir_up="$1"

if [ $dir_up -lt 1 ];then
  echo "Incorrect argument! Provide a number more than 0"
  exit
fi

i=1
sumdir=""
while [ $i -le $dir_up ]
 do
   dir="../"
   sumdir+=${dir}
   let i=$i+1
 done

cd $sumdir

After giving execution permission to the file, I put it under /bin folder BUT the point is I can’t simply run it like;

#up 4

and expect to move 4 directory levels up. I must run it inside the current shell I am in without forking any other process and here is the handy command “.” comes in. If I am in the following directory for example;

# pwd
/usr/libexec/gcc/x86_64-redhat-linux/4.5.1

running the command the following way;

# . up 2
[root@tux gcc]# pwd
/usr/libexec/gcc

will move us up to the /usr/libexec/gcc folder. The argument 2 here stands for in which directory we want to be above our working directory.

Although there may be a built-in bash command which already does this, I think it is good to see how “.” command can be this handy!

Tags:

About: rtoodtoo

Worked for more than 10 years as a Network/Support Engineer and also interested in Python, Linux, Security and SD-WAN, currently living in the Netherlands and works as a Network Support Engineer. // JNCIE-SEC #223 / RHCE / PCNSE


2 thoughts on “Moving up levels in directory tree easily”

  1. Hi Seth,
    I have just checked this autojump project. It is definitely great. I was indeed using primitive CDPATH environmental variable which is a way primitive than this project of course.
    It is good to know this one as well. Thanks for your feedback.

Leave a Reply to rtoodtoo Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.