带空格的Bash变量 [英] Bash variables with spaces

查看:186
本文介绍了带空格的Bash变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在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/TortoisePlink.exe执行二进制文件/c/Program.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆