Bash – Simplified navigation in terminal

aliasbashcd-commandshell

I know IDEs are the wave of the future, but I always find myself coding in vim in a Linux terminal. Old dog. New tricks.

Anyway, navigation becomes challenging when dealing with long package names. For instance, in my terminals I can see my current path as part of the prompt. Sometimes I am here:

/foo/bar/src/com/example/yomama/

and I want to get to:

/foo/bar

I have some nifty aliases:

alias 1down="cd .."
alias 2down="cd ..;cd .."
alias 3down="cd ..;cd ..;cd .."
alias 4down="cd ..;cd ..;cd ..;cd .."
alias 5down="cd ..;cd ..;cd ..;cd ..;cd .."

So if I type 4down, bam! I am at /foo/bar.

The thought just occurred to me that since I know my current working directory is:

/foo/bar/src/com/example/yomama/

I can also just go 2 up from / to get to /foo/bar.

So it would be cool to also implement a 2up function, since it is easier to count how many to go up. Before I start to write out a shell script for this, I am wondering if there are any shell tools that would lend a more elegant solution. Extra points if someone knows of one-liner that can implement Nup.

PS:
I already have

alias bar = "cd /foo/bar"

I am looking for a more generic solution here.

PPS: I have always thought that it would be really cool to have a clickable $PWD in the prompt. So I could just click on bar, and cd to /foo/bar. But maybe I should just move to a graphical IDE and shut up already 😉

EDIT:

There is some confusion on what my definition of Nup is.

Nup should take you to the Nth path location in your PWD from root. So, if you are currently in /a/b/c/d/e/f/g/h/i, 4up will take you to /a/b/c/d. Similarly 5down will get you /a/b/c/d.

Basically, you can navigate the path without having to laboriously 'cd ..' a bunch of times, or specifying 'cd /a/b/c/d'.

Best Answer

With two functions in your .bashrc file, you can use the directory stack for some navigation

function down ()
{
  if [[ -z "$1" ]]
  then
   n=1
  else
   n=$1
  fi

  for ((i=0; i<$n; i++ ));
  do
      pushd .. > /dev/null
  done;
}
function up ()
{
  if [[ -z "$1" ]]
  then
   n=1
  else
   n=$1
  fi

  for ((i=0; i<$n; i++ ));
  do
      popd > /dev/null
  done;
#  dirs -c  # To clear directory on up motion
}

Where you can use down N and up N, respectively.

Sample usage:

~/tmp/bash/dir1/dir2/dir3$ down 4
~/tmp$ up 2
~/tmp/bash/dir1$ up 2
~/tmp/bash/dir1/dir2/dir3$ down 2
~/tmp/bash/dir1$ down 1
~/tmp/bash$ up 3
~/tmp/bash/dir1/dir2/dir3$

Of course, you cannot use up N before using down N. Unexpected things might happen, or error messages may appear.