Bash 使用 subshell 和 substring 进行错误替换
一个人为的例子......考虑到
FOO="/foo/bar/baz"
这个工作(在bash中)
BAR=$(basename $FOO) # result is BAR="baz"
BAZ=${BAR:0:1} # result is BAZ="b"
这不是
BAZ=${$(basename $FOO):0:1} # result is bad substitution
我的问题是哪个规则导致这个[子shell替换]评估不正确?在 1 跳中执行此操作的正确方法(如果有)是什么?
A contrived example... given
FOO="/foo/bar/baz"
this works (in bash)
BAR=$(basename $FOO) # result is BAR="baz"
BAZ=${BAR:0:1} # result is BAZ="b"
this doesn't
BAZ=${$(basename $FOO):0:1} # result is bad substitution
My question is which rule causes this [subshell substitution] to evaluate incorrectly? And what is the correct way, if any, to do this in 1 hop?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
发布评论
评论(6)
~没有更多了~
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
首先,请注意,当您这样说时:
BAZ
构造中的第一位是BAR
,而不是您想要采用的值的第一个字符。因此,即使 bash 允许变量名称包含任意字符,第二个表达式中的结果也不会是您想要的。然而,至于阻止这种情况的规则,请允许我引用 bash 手册页:
然后稍后:
然后当它定义您要询问的语法时:
因此,手册页中阐明的规则说 < code>${foo:x:y} 构造必须有一个参数作为第一部分,并且参数只能是名称、数字或少数特殊参数字符之一。
$(basename $FOO)
不是参数允许的可能性之一。至于在一项作业中执行此操作的方法,请使用其他响应中提到的其他命令的管道。
First off, note that when you say this:
the first bit in the construct for
BAZ
isBAR
and not the value that you want to take the first character of. So even if bash allowed variable names to contain arbitrary characters your result in the second expression wouldn't be what you want.However, as to the rule that's preventing this, allow me to quote from the bash man page:
Then a bit later:
And later when it defines the syntax you're asking about:
So the rules as articulated in the manpage say that the
${foo:x:y}
construct must have a parameter as the first part, and that a parameter can only be a name, a number, or one of the few special parameter characters.$(basename $FOO)
is not one of the allowed possibilities for a parameter.As for a way to do this in one assignment, use a pipe to other commands as mentioned in other responses.