6

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. – Mark Plotnick Nov 17 '14 at 16:02
  • I generally use bash. – Stephen Schrauger Nov 17 '14 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. – Gilles Nov 18 '14 at 8:10
6

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.

2

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
}
2

In ksh or zsh:

cd dev staging

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.