user134909
user134909

Reputation: 33

Can't export environment variable in WSL

I feel like I am having a stroke. I am currently running the following export command in WSL:

export BROWSER=/mnt/c/Program\ Files/Mozilla\ Firefox/firefox.exe

but WSL doesn't seem to recognize that $BROWSER has been overwritten as it keeps running it without the backslashes:

echo $BROWSER
/mnt/c/Program Files/Mozilla Firefox/firefox.exe

Which causes the following error when running the command:

$BROWSER
bash: /mnt/c/Program: No such file or directory

Is this a bug in WSL? Or have I made a mistake setting environment variables?

EDIT:

I also tried it using quotes instead of slashes:

export BROWSER='/mnt/c/Program Files/Mozilla Firefox/firefox.exe'

Upvotes: 2

Views: 3373

Answers (1)

Kurtis Rader
Kurtis Rader

Reputation: 7459

Welcome to the painful world of POSIX compatible shell behavior.

The backslashes in the assignment "escape" the space characters. Which means they are not treated as whitespace that would normally terminate the string. The backslashes are removed because they served their purpose. This has nothing to do with environment variables. It's how backslashes work in a POSIX shell. Try echo a\ b\"c.

Then, when you used $BROWSER, the shell replaced that variable reference with the value of the variable. It then split the result on the value of the $IFS variable. Since $IFS normally contains space, tab, and newline the browser path was split on the embedded spaces into three distinct strings. You can see this happen by running printf "%s\n" $BROWSER.

The solution is to quote the variable expansion to inhibit the $IFS splitting. In other words, use "$BROWSER". In fact, you should almost always place variable expansion inside double-quotes.

Upvotes: 4

Related Questions