changing to parent directory in unix

Vijay picture Vijay · Dec 9, 2009 · Viewed 40.5k times · Source

in general we use

cd .. for going to the parent directory

cd ../../ to go to the parents parent directory. and

cd ../../../../../ for 5th parent directory.

is there any simplified way of doing this?

shell i am using is ksh.

Answer

Dennis Williamson picture Dennis Williamson · Dec 9, 2009

This function is for Bash, but something similar could be done for others (this may work as-is in ksh and zsh):

cdn () { pushd .; for ((i=1; i<=$1; i++)); do cd ..; done; pwd; }

Example usage:

/some/dirs/and/subdirs$ cdn 3
/some/dirs/and/subdirs /some/dirs/and/subdirs
/some
/some$ popd
/some/dirs/and/subdirs$

Here's a function that will cd to a named subdirectory above the current working directory:

cdu () { cd "${PWD%/$1/*}/$1"; }

Example usage:

/usr/share/atom/resources/app/apm/src/generator$ cdu apm
/usr/share/atom/resources/app/apm$ cdu resources
/usr/share/atom/resources$ cd -
/usr/share/atom/resources/app/apm$ cdu share
/usr/share