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

Creating a shell function to move up multiple directory levels using the "cd" command

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.


Hope you found this post useful. It was published . Please show your love and support by sharing this post.