Bash variables with spaces

纵然是瞬间 提交于 2019-11-27 13:30:29

Execute it like this: "$VAR". This is one of the most significant gotchas in shell scripting because strings are always substituted literally and any contained spaces are treated as token delimiters rather than as characters of the string. Think of substituting a variable as a kind of code pasting at runtime.

What really happens when you write $VAR is that the shell tries to execute the binary /c/Program with a first argument Files/TortoiseGit/bin/TortoisePlink.exe.

I learned this the hard way by getting a strange syntax error in a big shell script for a particular input. No other languages I can think of can complain for syntax errors if the runtime input contains special characters - but that is the nature of shell scripting since command interpreters like bash and sh interpret the code line by line.

Whenever you expect a string to contain spaces and you don't want to treat it as separate tokens, enclose it in double quotes.

For reference, I solved a similar issue on osx by encapsulating the argument with escaped quotations. This may not be the best solution, but it seems to work.

alias sub="\"/Applications/Sublime Text 2.app/Contents/SharedSupport/bin/subl\""
Dubilyer

I've solved it by including a backslash to escape the space:

/Program Files becomes /Program\ Files

Example:

export GIT_SSH=/c/Program\ Files/TortoiseGit/bin/TortoisePlink.exe

With Git 2.23 (Q3 2019, eight years later), a GIT_SSH set to /c/Program\ Files/TortoiseGit/bin/TortoisePlink.exe will... work (for those still on Widows 7)!

See commit eb7c786 (16 Jul 2019) by Johannes Schindelin (dscho).
(Merged by Junio C Hamano -- gitster -- in commit a5194d8, 25 Jul 2019)

mingw: support spawning programs containing spaces in their names

On some older Windows versions (e.g. Windows 7), the CreateProcessW() function does not really support spaces in its first argument, lpApplicationName.
But it supports passing NULL as lpApplicationName, which makes it figure out the application from the (possibly quoted) first argument of lpCommandLine.

Let's use that trick (if we are certain that the first argument matches the executable's path) to support launching programs whose path contains spaces.

This fixes git-for-windows/git issue 692

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!