首先要注意,当你说这句话时:
BAR=$(basename $FOO)
BAZ=${BAR:0:1}
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.
所以,man页中规定的规则是,${foo:x:y}
结构必须有一个参数作为第一部分,而参数只能是名称、数字或少数特殊参数字符之一。 $(basename $FOO)
不是允许作为参数的选项之一。
至于如何在一次赋值中完成此操作,请使用其他响应中提到的管道到其他命令的方式。