bash 如何知道我的变量名在哪里结束?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3497202/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How does bash know where my variable names end?
提问by sunny8107
Given:
鉴于:
myvar=Hello
echo $myvar-> ShowsHello(fine so far)echo $myvar#world-> showsHello#world(why? I thought it would complain that here is no such variable calledmyvar#world)echo ${myvar#world}-> shows justHello(again, why?)
echo $myvar-> 节目Hello(到目前为止还好)echo $myvar#world-> 显示Hello#world(为什么?我以为它会抱怨这里没有这样的变量叫做myvar#world)echo ${myvar#world}-> 只显示Hello(再次,为什么?)
回答by Douglas
The second case splits up into three parts:
第二种情况分为三个部分:
[echo] [$myvar][#world]
1 2 3
Part 1 is the command, part 2 is a parameter, and part 3 is a string literal. The parameter stops on rsince the #can't be part of the variable name (#'s are not allowed in variable names.)
第 1 部分是命令,第 2 部分是参数,第 3 部分是字符串文字。参数停止,r因为#不能是变量名的一部分(变量名中不允许使用#。)
The shell parser will recognise the start of a parameter name by the $, and the end by any character which cannot be part of the variable name. Normally only letters, numbers and underscores are allowed in a variable name, anything else will tell the shell that you're finished specifying the name of the variable.
shell 解析器将通过 识别参数名称的开始$,以及任何不能作为变量名称一部分的字符的结尾。通常,变量名中只允许使用字母、数字和下划线,其他任何内容都会告诉 shell 您已完成指定变量的名称。
All of these will print out $myvarfollowed by six literal characters:
所有这些都将打印出来,$myvar后跟六个文字字符:
echo $myvar world
echo $myvar?world
echo $myvar#world
If you want to put characters which can be part of a parameter directly after the parameter, you can include braces around the parameter name, like this:
如果要在参数后直接放置可以作为参数一部分的字符,可以在参数名称周围包含大括号,如下所示:
myvar=hello
echo ${myvar}world
which prints out:
打印出来:
helloworld
Your third case is substring removal, except without a match. To get it to do something interesting, try this instead:
您的第三种情况是子字符串删除,除非没有匹配项。为了让它做一些有趣的事情,试试这个:
myvar="Hello World"
echo ${myvar#Hello }
which just prints World.
只打印World.
回答by ennuikiller
variables cannot contain a "#" so the shell knows its not part of a variable.
变量不能包含“#”,所以 shell 知道它不是变量的一部分。
The construct ${myvar#world} actually is a string manipulator explained below:
构造 ${myvar#world} 实际上是一个字符串操作符,解释如下:
# is actuially a string modifier that will remove the first part of the string matching "world". Since there is no string matching world in myvar is just echos back "hello"
# 实际上是一个字符串修饰符,它将删除与“world”匹配的字符串的第一部分。由于 myvar 中没有字符串匹配世界只是回声“你好”

