首先,請注意,當你這樣說:
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)
不是參數允許的可能性之一。
至於如何在一個賦值中執行此操作,請使用其他響應中提到的其他命令的管道。