Here's a function that does what you want:
cdto () { cd "${PWD%/$1/*}/$1"; }
Here's another handy one:
c2 () {
local path num
if (($# != 0))
then
path='./'
fi
if [[ -z ${1//.} ]]
then
num=${#1}
elif [[ -z ${1//[[:digit:]]} ]]
then
num=$1
else
echo "Invalid argument"
return 1
fi
for ((i=0; i<num-1; i++))
do
path+='../'
done
cd $path
}
Usage:
c2 . # same as cd .
c2 .. # same as cd ..
c2 ... # same as cd ../..
c2 3 # also same as cd ../..
c2 # same as cd (which is the same as cd ~)
I thought one of the shells used to have the cumulative dot-dot-dot feature (I even checked Vista just now and it didn't have it although Google claims that some versions of Windows do).
Edit
An undocumented feature of Bash is that a lot of characters are acceptable in function names. As a result, you can do this:
.. () { cd ..; }
... () { cd ../..; }
.... () { cd ../../..; }
..... () { cd ../../../..; }
Thanks, the small function you posted is exactly what I asked for, except this: how can I use it as a command in the shell? It works inside a shell script, cd in a shell doesn't affect the pwd of the shell that called it. I tried putting it into an alias, which didn't work either. Any suggestions? – Haakon – 2010-06-02T21:18:33.903
1@haakon: Put the function in a file and source the file using
. filename
. That adds the function to the current environment. You could also simply add the function definition to your~/.bashrc
file or, like I do, put it in a file with other functions called~/bin/functions
then in my~/.bashrc
I have a statement that sources that file. ~/bin/functions
. – Paused until further notice. – 2010-06-02T22:52:18.677