Tuesday, October 24, 2006

dot dot

If you need to do a lot cd ../../../, this little function may save you a lot of typing.
..()
{
  odir=`pwd`
  cnt=${1:-1}
  expr $cnt / 1 > /dev/null 2>&1

  # number
  if [ $? -eq 0 ]; then
    while [ $cnt -gt 0 ]; do
      cd ..
      cnt=`expr $cnt - 1`
  done
  else
    cdir=`pwd`
    while [ "$cdir" != "/" ]; do
      cd ..
      cdir=`pwd`
      if [ `basename $cdir` == "$cnt" ]; then
        return
      fi
    done
    cd $odir
  fi
}
Example:
$ mkdir -p /a/b/c/d/e/f/g
$ cd /a/b/c/d/e/f/g
$ .. 3
$ pwd
/a/b/c/d
$ cd /a/b/c/d/e/f/g/
$ .. b
$ pwd
/a/b
$ .. x
$ pwd
/a/b/c/d/e/f/g

Labels: ,