Bash – n easy way to change directories from within one duplicate folder structure to another

bashcd-commanddirectory

On our server, we have several duplicate-ish folder structures for testing, staging, and production. Other than minor changes, the folder structure between all three are generally the same.

When I'm working on a WordPress plugin, I'm deep within the development folder structure (ex ~/dev/com/wp-content/plugins/myplugin). I know that ~/staging/com/wp-content/plugins/myplugin exists.

If my current working directory is ~/dev/com/wp-content/plugins/myplugin, can I somehow easily switch to ~/staging/com/wp-content/plugins/myplugin without typing the entire directory structure?

I'd like to type something like cdx~/staging, or even cdx../../../../../staging and have the command try to traverse down the new directory using my current directory path. Obviously, if the new folder doesn't contain the proper structure, it would error out.

Am I stuck typing the entire directory structure? Or is there a better way?

Best Answer

Use string substitution in bash:

$ a="~/dev/com/wp-content/plugins/myplugin"
$ echo ${a/dev/staging}
~/staging/com/wp-content/plugins/myplugin

So a function like:

cdx () 
{
    cd "${PWD/$1/$2}"
}

And then do cdx dev staging to switch from a folder in dev to staging. With some checks, you could name the function cd:

cd ()
{
    if [ $# != 2 ]
    then
        builtin cd "$@"
    else
        builtin cd "${PWD/$1/$2}"
    fi
}

Effect:

~ # cd /tmp
/tmp # cd tmp srv
/srv # cd
~ # cd -
/srv
/srv # cd tmp var
/srv #

This retains the usual behaviour of cd in all cases, except for two arguments.

Related Question