Tiny Code

Tiny Code

Tuesday, February 24, 2015

Changing to a sibling directory easily

I deal with multiple source trees on a daily basis.  Occasionally it's handy to switch from a subdirectory in one to the same subdirectory in a different source tree.  So I put together the following set of shell functions (similar to command aliases but they allow greater flexibility in checking parameters) to make this easier.

For example, let's suppose my current directory is ~/src/tree1/subdir1/subdir2/subdir3/ and I want to switch to the same path in the directory ~/src/tree2.  With these bash functions defined, I can type the command "cds tree1 tree2".  If I want to return to the previous directory, I can hit the up arrow key to recall the command, cursor over, and change the "cds" command to "cdsb".

# cd sideways (replaces one portion of current path with new string and changes to that directory)
function    cds
{
    if [ -z "$2" ]                           # Is parameter #1 zero length?
    then
        echo "Usage: cds DirPatternToReplace DirNewPattern"
    else
        NWD=`echo $PWD | sed -e "s/$1/$2/"`
        echo "Changing directory"
        echo "from: $PWD"
        echo "to:   $NWD"
        cd $NWD
    fi
}

# cd sideways back (same as previous command but parameters are reversed to go backwards)
function    cdsb
{
    if [ -z "$2" ]                           # Is parameter #1 zero length?
    then
        echo "Usage: cdsb DirPatternToReplace DirNewPattern"
    else
        NWD=`echo $PWD | sed -e "s/$2/$1/"`
        echo "Changing directory"
        echo "from: $PWD"
        echo "to:   $NWD"
        cd $NWD
    fi
}

No comments: