cd to directory determined by pipelined commands

Viewed 49

I'm trying to parse a Window Title that contains a path and then cd to that directory. My command successfully returns the directory I want to go to but I'm getting weird problems when trying to cd to it. The window title looks like this: C:\path\to\directory\file.cpp (bullet point)- Program name. Because of the weird bullet point symbol I'm cutting on the . in .cpp and then getting the parent directory of what it thinks is a subdirectory but is really a file. Still works fine. The command is

cd $(dirname $(tasklist -fi "imagename eq sublime_text.exe" -fo list -v | grep "Window Title" | cut -f1 -d. | cut -d: -f2- | cut -c 2-) | sed 's/^/"/ ;s/$/"/')

When I replace cd with echo I get "C:\path\to\directory" and when I simply type cd and copy paste this quoted path that I get back it works. But it will not work in the command, I get bash: cd: "C:\Users\twilliams\Documents\GitHub\Native\mcs\src\Lib": No such file or directory. I have also tried putting quotes around the cd and dirname commands like so

cd "$(dirname "$(tasklist -fi "imagename eq sublime_text.exe" -fo list -v | grep "Window Title" | cut -f1 -d. | cut -d: -f2- | cut -c 2-)" | sed 's/^ /"/;s/$/"/')"

Additionally I tried it using echo instead of sed like so

cd "$(echo "\"$(dirname "$(tasklist -fi "imagename eq sublime_text.exe" -fo list -v | grep "Window Title" | cut -f1 -d- | cut -d: -f2- | cut -c 2-)") \"")"

In all of these cases I get the proper "C:\path\to\directory" output when echoing, and cding to this path manually works

I'm using git bash on windows. Thoughts?

1 Answers

Stop inserting literal quotes -- unlike syntactic quotes they're treated as part of the directory name itself, and there isn't a drive named "C or a directory named directory" on your system. This can be as simple as just taking out the sed invocation:

cd "$(dirname "$(tasklist -fi "imagename eq sublime_text.exe" -fo list -v |
                 grep "Window Title" |
                 cut -f1 -d. |
                 cut -d: -f2- |
                 cut -c 2-)")"

By the way, I'd also suggest using cygpath to convert your Windows-style filename over to a natively-UNIXy one that doesn't require cygwin-specific magic to be processed.

Related