Shell - Navigate up 'n' directories
No, there is no existing command for this, but it is trivial to write one. Add these lines to your ~/.bashrc
file (thanks to D. Ben Knoble for pointing out that the variable should be local
):
function ncd(){
local path=""
for ((i=1;i<=$1;i++)); do
path="../$path"
done
echo "Moving to $path" >&2
cd "$path"
}
Save the file, open a new terminal, and you can now move N directories up using ncd N
. For example:
$ pwd
/home/terdon/dir1/dir2/dir3/dir4/dir5/dir6/dir7/dir8/dir9
$ ncd 5
Moving to ../../../../../
$ pwd
/home/terdon/dir1/dir2/dir3/dir4
$ ncd 2
Moving to ../../
$ pwd
/home/terdon/dir1/dir2
Coming from the Windows world, Alt + Up Arrow navigates to the parent directory
in Windows Explorer. So I made something like this in ~/.inputrc
:
"\33\33[A": "cd ..\n"
then pressing Alt + Up Arrow moves to the parent directory in the terminal. You have to press multiple times of course to move higher, but I have found it to be very fast. Also you can change the shortcut to your liking.
You can easily create aliases or shell functions to perform the given task. I personally use these:
alias ..='cd ..'
alias ...='cd ../..'
alias ....='cd ../../..'
and so on, manually defined for up to many-many dots in my .bashrc
.
A shell function could instead easily take a numeric parameter, and execute cd ..
in a loop that many times.