首先,请注意,当你这样说:
BAR=$(basename $FOO) # result is BAR="baz"
BAZ=${BAR:0:1} # result is BAZ="b"
在构建BAZ
第一位是BAR
而不是值要采取的第一个字符。所以,即使bash允许变量名包含任意字符,第二个表达式中的结果也不会是你想要的。
然而,由于该问题,导致这个规则,让我从bash的手册页引用:
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).
后来当它定义的语法你问的是:
${parameter:offset:length}
Substring Expansion. Expands to up to length characters of
parameter starting at the character specified by offset.
因此,在手册页中阐明的规则说${foo:x:y}
结构必须有一个参数作为第一部分,并且参数只能是名称,数字或少数特殊参数字符之一。 $(basename $FOO)
不是参数允许的可能性之一。
至于如何在一个赋值中执行此操作,请使用其他响应中提到的其他命令的管道。