Unix terminal, "cd .." for a certain number of directories

Suppose we have this directory structure:

/home/myuser/dir_1/sub_1/sub_2/sub_3

and I want to switch from sub_3 to dir_1, I need to do

cd ../../..

My question is: is there anything shorter? I mean something like:

cd -t 3

where you can tell the shell how many directories you want to return.

+4
source share
5 answers

Build the path using printf, then cdto it:

cdup() {
    # $1=number of times, defaults to 1
    local path
    printf -v path '%*s' "${1:-1}"
    cd "${path// /../}"
}

Use as:

cdup 4 # to go up four directories
cdup 1 # to explicitly go up one directory
cdup   # to implicitly go up one

Does the nice property have what cdis called once, no matter how large N.

+3
source

for I'm in {0..2}; do cd ..; done

+1
source
cd ~/dir_1

Gotta do the same. Of course, this only works when you go somewhere to your home directory ....

+1
source

I just completed the Zsh completion function just a couple of weeks ago to do this. The answer is here .

It allows you to enter cd ....., then click a tab (or return) to expand the points in the corresponding number of directories.

0
source

You can put cdup in your .bashrc

 alias cdup='_(){ a=$1;while ((a--));do cd ..;done;};_'

or

cdup() { a=$1;while ((a--));do cd ..;done; }

Check to make two cd ..

cdup 2
0
source

Source: https://habr.com/ru/post/1666728/


All Articles