How to Create a Shortcut to Move Up Multiple Directory Levels in a Shell?

There is no built-in shortcut for moving up multiple levels in a directory structure using the cd shell command. However, you can create your own shortcut by defining a function in your shell configuration file (e.g. in .bashrc file for the bash shell, .zshrc file for the zsh shell, etc.), for example, like so:

function up {
  for i in $(seq "$1"); do
    cd ../
  done
}

As an alternative, you could use the following function that repeats the ../ string "n" number of times (as specified via the command line argument):

function up() {
  cd $(printf "%.s../" $(seq "$1"));
}

Both of the functions above, use the seq command to generate a sequence of ../ strings, one for each level you want to move up. The number of levels is specified as the first command line argument passed to the function. You can call this function like so:

up 3

This would move up three levels in the directory structure.

If the shell you're using does not support functions, then you may try using aliases instead. However, most shells do not allow passing arguments/parameters to aliases.


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.