Skip to content

Instantly share code, notes, and snippets.

@moregeek
Last active December 18, 2015 08:42
Show Gist options
  • Save moregeek/f6faf1b744cba8b131e6 to your computer and use it in GitHub Desktop.
Save moregeek/f6faf1b744cba8b131e6 to your computer and use it in GitHub Desktop.
extends "cd" to accept (multiple) "dots" as indicator to traverse the directory tree up
#
# Copyright (C) 2015 Stefan Morgenthaler
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
#
# extends "cd" to accept (multiple) "dots" as indicator to traverse
# the directory tree up.
#
# usage/example:
#
# $ pwd # => /f/o/0/b/a/r/
#
# $ cd .. && pwd # => /f/o/0/b/a/
# $ cd ... && pwd # => /f/o/0/b/
# $ cd .... && pwd # => /f/o/0/
# $ cd ..... && pwd # => /f/o/
#
# $ cd ............ && pwd # => /
#
# howto use:
#
# source <path_to_this_script>
#
function cd () {
local cdargs="${cdargs:=${@:1:$(($#-1))}}"; # $1 .. (n-1)
local cdpath="${@:$#}"; # n-th element (last)
local cdnpath="";
while [ "${cdpath:0:2}" == ".." ]; do
cdpath=${cdpath/\.}; cdnpath+="../";
done && cdnpath=${cdnpath}${cdpath/\.\/}
builtin cd ${cdargs} ${cdnpath:-${cdpath}}
}
# vim: set ts=2 sw=2 tw=80 ft=sh et :
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment