Reputation: 666
Let's suppose we have this directory structure:
/home/myuser/dir_1/sub_1/sub_2/sub_3
and I want to traverse from sub_3 to dir_1, what I need to do is
cd ../../..
My question is, isn't there something shorter? I mean something like:
cd -t 3
where you can tell the shell how many directories you want to go back.
Upvotes: 5
Views: 495
Reputation: 39464
Build the path using printf
then cd
to 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
Has the nice property that cd
is called once, regardless of how big N is.
Upvotes: 4
Reputation: 1619
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; }
Test to make two cd ..
cdup 2
Upvotes: 0
Reputation: 38620
I just a couple of weeks ago made a Zsh completion function to do this. The answer is here.
It allows you to type cd .....
then hit tab (or return) to expand the dots into the relevant number of directories.
Upvotes: 0
Reputation: 2225
cd ~/dir_1
Should do the same as well. Of course, that only works when you are going somewhere in your home directory....
Upvotes: 1