带空格的 Bash 变量 [英] Bash variables with spaces
问题描述
我在 windows 下的 MinGW shell 中面临下一个问题.我的 /etc/profile
中有表达式:
I'm facing the next problem in MinGW shell under windows. I have in my /etc/profile
the expression:
export GIT_SSH="/c/Program Files/TortoiseGit/bin/TortoisePlink.exe"
当我在本地存储库上使用 git fetch
时,这不起作用.但是如果我这样做(旧的 DOS 方式),它就可以工作:
This doesn't work when I use git fetch
on the local repository. But if I do it like this (old DOS way), it works:
export GIT_SSH="/c/Progra~1/TortoiseGit/bin/TortoisePlink.exe"
我的问题是:
如何使用变量中的空格使其工作?
How can I make it work using spaces in the variable?
出于测试目的,您可以模拟这样的事情(任何示例都很好):
For testing purpose you can simulate something like this (any example is good):
export VAR="/c/Program Files/TortoiseGit/bin/TortoisePlink.exe"
# and try to execute like this
$VAR
是否有解决方案(除了前面提到的)?
Is there a solution for this (other than the previous mentioned)?
推荐答案
像这样执行:"$VAR"
.这是 shell 脚本中最重要的问题之一,因为字符串总是按字面意思替换,并且任何包含的空格都被视为标记分隔符而不是字符串的字符.将变量替换为运行时的一种代码粘贴.
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.
当你编写 $VAR
时真正发生的事情是 shell 尝试使用第一个参数 Files/TortoiseGit/bin 执行二进制
./c/Program
/TortoisePlink.exe
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
.
通过在特定输入的大型 shell 脚本中出现奇怪的语法错误,我学到了这一点.如果运行时输入包含特殊字符,我能想到的其他语言都不会抱怨语法错误 - 但这是 shell 脚本的本质,因为像 bash 和 sh 这样的命令解释器逐行解释代码.
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.
这篇关于带空格的 Bash 变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!