Victor Quinn

Software Engineer, Legal Scholar, Problem Solver.

Cd Which Directory

Sharing a minor tweak which has been very useful to me.

I find I often want to cd into the directory where a program exists. Let’s say I was trying to jump to the directory which contained myawesomeprogram but didn’t know where it was. My old workflow was something like:

1
2
3
which myawesomeprogram
# Manually click/drag to copy and paste the resulting output
cd <pasted directory>

Come on, I’m an übernerd, surely I can figure out something better/more efficient which doesn’t require me to touch my mouse.

Enter a simple zsh function

I use zsh for my shell. I think this should work with bash though YMMV.

1
2
3
cdw () {
  cd $(dirname $(which $1))
}

Adding this to my .zshrc allows me to just type

1
cdw myawesomeprogram

and I’m immediately teleported to the folder which contains that program.