Advertisement
haiv

A cd replacement which goes up many levels

May 9th, 2017
310
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 1.01 KB | None | 0 0
  1. # ======================================================================
  2. # A replacement for the built-in cd command which understands multiple
  3. # dots. For example:
  4. #
  5. #     cd ...    # Up 2 levels
  6. #     cd ....   # Up 3 levels
  7. #     cd .....  # Up 4 levels
  8. # ======================================================================
  9. function cd() {
  10.     if [[ "$1" =~ ^\.\.\.+$ ]]
  11.     then
  12.         # Case: The argument contains 3 or more dots and no other chars
  13.  
  14.         local levels=${1/./}  # How many levels to go up
  15.         local destination=.   # The final destination
  16.  
  17.         # Each time we go through the loop, we go up one level and
  18.         # remove one dot from levels
  19.         while [[ -n $levels ]]
  20.         do
  21.             destination=$destination/..
  22.             levels=${levels/./}
  23.         done
  24.  
  25.         cd $destination
  26.     else
  27.         # If the argument does not contain 3 or more dots, we will treat
  28.         # it as a regular case
  29.         builtin cd "$@"
  30.     fi
  31.  
  32.     ls  # Nice to have
  33. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement