haiv icon

A cd replacement which goes up many levels

haiv | PRO | 05/09/17 02:38:33 PM UTC | 0 ⭐ | 434 👁️ | Never ⏰ | []
Bash |

1.01 KB

|

None

|

0 👍

/

0 👎

# ======================================================================
# A replacement for the built-in cd command which understands multiple
# dots. For example:
#
#     cd ...    # Up 2 levels
#     cd ....   # Up 3 levels
#     cd .....  # Up 4 levels
# ======================================================================
function cd() {
    if [[ "$1" =~ ^\.\.\.+$ ]]
    then
        # Case: The argument contains 3 or more dots and no other chars
 
        local levels=${1/./}  # How many levels to go up
        local destination=.   # The final destination
 
        # Each time we go through the loop, we go up one level and
        # remove one dot from levels
        while [[ -n $levels ]]
        do
            destination=$destination/..
            levels=${levels/./}
        done
 
        cd $destination
    else
        # If the argument does not contain 3 or more dots, we will treat
        # it as a regular case
        builtin cd "$@"
    fi
 
    ls  # Nice to have
}

Comments