问题描述
一个人为的例子...给出
A contrived example... given
FOO="/foo/bar/baz"
这工作(在bash)
this works (in 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
我的问题是哪个规则导致此[壳层替代]无法正确评价?什么是正确的方法,如果有的话,在1跳这样做吗?
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?
推荐答案
首先,请注意,当你这样说:
First off, note that when you say this:
BAR=$(basename $FOO) # result is BAR="baz"
BAZ=${BAR:0:1} # result is BAZ="b"
在构建 BAZ第一位
是 BAR
,而不是值的要采取的第一个字符。所以,即使允许bash的变量名包含任意字符你的结果在第二个前pression不会是你想要的。
the first bit in the construct for BAZ
is BAR
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.
不过,对于这preventing此规则,请允许我从bash的手册页引述如下:
However, as to the rule that's preventing this, allow me to quote from the bash man page:
DEFINITIONS
The following definitions are used throughout the rest of this docu‐
ment.
blank A space or tab.
word A sequence of characters considered as a single unit by the
shell. Also known as a token.
name A word consisting only of alphanumeric characters and under‐
scores, and beginning with an alphabetic character or an under‐
score. Also referred to as an identifier.
然后稍后:
PARAMETERS
A parameter is an entity that stores values. It can be a name, a num‐
ber, or one of the special characters listed below under Special Param‐
eters. A variable is a parameter denoted by a name. A variable has a
value and zero or more attributes. Attributes are assigned using the
declare builtin command (see declare below in SHELL BUILTIN COMMANDS).
后来当它定义你问有关语法:
And later when it defines the syntax you're asking about:
${parameter:offset:length}
Substring Expansion. Expands to up to length characters of
parameter starting at the character specified by offset.
因此,作为挂接在手册页的规则说, $ {foo的:X:Y}
构造必须有一个参数作为第一个部分,一个参数可以仅是一个名称,号码,或一些特殊的参数字符之一。 $(基名$ FOO)
不是为某个参数允许的可能性之一。
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.
这篇关于巴什坏替换与子shell和子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!