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?

  • What shell do you use? Some shells will make what you want to do a bit easier. Nov 17, 2014 at 16:02
  • I generally use bash.
    – Stephen S
    Nov 17, 2014 at 16:06
  • 2
    In zsh, you simply do cd dev staging. I think I remember a question on this site where someone had posted bash code to do the same (a more elaborate version of muru's answer), but I can't find it. Nov 18, 2014 at 8:10

3 Answers 3


Use string substitution in bash:

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

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 ]
        builtin cd "$@"
        builtin cd "${PWD/$1/$2}"


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

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


Add this function to your .bash_profile and typing cdstaging you will be able to change between any directory inside ~/dev to the equivalent on ~/staging.

Of course you can change the name for whatever you want. Additionally, you could create a reverse function just changing function name and "1s@dev@staging@" to just the opposite.

cdstaging ()
        OLDPATH=$(pwd | sed -e "1s@$HOME@~@")
        NEWPATH=$(echo $OLDPATH | sed -e "1s@dev@staging@")
        cd $NEWPATH

In ksh or zsh:

cd dev staging

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .