How to cd to the path returned by which?

0

I'm curious how I might be able to change directory to the directory returned by which. I was hoping for a simple one liner like which whatimlookingfor | cd but it only prints my current directory. In a windows command prompt, is there a quick way to do this?

Corey Ogburn

Posted 2013-12-12T22:01:37.837

Reputation: 551

Answers

0

You'll need to use dirname to get the directory of the thing you are looking for with which.

cd `dirname \`which whatimlookingfor\``

Note the use of backtick rather than quotes or something else.

On Windows, where you may not have access to bash via cygwin or MSys, you can use powershell rather than cmd.exe to accomplish the same.

Substitution in powershell is accomplished via $( ) so your command might look something like this:

cd $(dirname $(which whatimlookingfor))

Assuming you have dirname binary also available in path.

ssnobody

Posted 2013-12-12T22:01:37.837

Reputation: 2 510

Tried this, and it's close. Something I forgot about which is that it also contains the file in the path. So if I call which xcopy I get C:\Windows\system32\xcopy.EXE. How can I remove the file and just have the path? – Corey Ogburn – 2013-12-12T23:12:30.513

Your return from which indicates you are using windows. I'm not too sure about nested backtick operators in cygwin or the like, so you may have to investigate that if the above does not work. Above works fine for me from bash shell on linux. – ssnobody – 2013-12-12T23:16:00.860

I don't think the backticks help at all on windows... I may need another question. – Corey Ogburn – 2013-12-12T23:19:38.983