Home > Net >  How to export a windows path and then cd to is using the variable?
How to export a windows path and then cd to is using the variable?

Time:04-15

I typically export variables with directories/paths that I frequently visit so that I don't have to type the whole thing (or tab). For example, in Windows, I'll create an environment variable and then use it in a bash prompt (git bash): cd $MY_LONG_PATH

Or, I can export a path in my .bashrc and use it the same way. Both ways work fine until you add spaces into the mix. For example, I'd like to be able to export a path like C:\Users\name\OneDrive - Company, Inc\Documents\My Project Folder\. You might say, just use a different directory. Unfortunately, I can't change this one because it's controled by my org. So, considering I can't change it, how can I get it to work with an environment or exported variable? I've tried both ways, but can't seem to get it right. I've escaped all the chars in .bashrc c\:/Users/name/OneDrive\ -\ Company,\ Inc/Documents/My\ Project\ Folder. This will work on the bash cli when I type it in (terminal), but doesn't work when I export it as a variable. I've tried using quotes around the whole thing and that doesn't work either. I've tried it in the regular windows environment variable control panel, and that doesn't work. Does anyone know the fix, if there is one?

Again, the goal is just to be able to: cd $LONG_PATH with the variable containing a windows directory with spaces

CodePudding user response:

My test on Gitbash

# remove the trailing backslash
MY_LONG_PATH="C:\Users\name\OneDrive - Company, Inc\Documents\My Project Folder"   <---
# use quotes
$ ls -l "$MY_LONG_PATH"
total 0
drwxr-xr-x 1 user 197613 0 Apr 14 00:10 test/
$ cd "$MY_LONG_PATH"
$ pwd
/c/Users/name/OneDrive - Company, Inc/Documents/My Project Folder
$ ls
test/ 

CodePudding user response:

I figured out a way to do this. While ufopilot's answer was good, I didn't like having to use quotes for variables that have special characters. Also, I found that when you use tab-completion, there's a bug in bash (bash-completion) that will escape the $ in a variable on the command-line, which in turn would break the directory path. So to fix all of this, I first created a soft symlink to the path that contains spaces using Windows cmd:

> mklink /D C:\Users\name\projects "C:\Users\name\OneDrive - Company, Inc\Documents\My Project Folder"

And now I can export the variable in .bashrc:

export LONG_PATH="C:\Users\name\projects"

This allows me to change directories without putting quotes around LONG_PATH:

> cd $LONG_PATH

To fix the problem with tab-completion, I had to run the bash command:

shopt -s direxpand

What this does is it expands the variable first and then escapes the special characters if needed (for example, if yet another directory has spaces). Everything works like my other path variables now!

  • Related