变量名可以包含“-”吗?

变量名可以包含“-”吗?
$ my-num=1
my-num=1: command not found

$ mynum=1

我想知道为什么第一次作业失败了?

为什么bash认为它是一个命令?

-bash 中有一些特殊字符吗?

谢谢。

答案1

POSIX 标准规定如下:

3.229 名称

3.229 Name
In the shell command language, a word consisting solely of underscores, digits, and 
alphabetics from the portable character set. The first character of a name is not a digit.

在 Shell 语法规则的 POSIX 标准部分中,它指出:

2.10.2 Shell语法规则

7. [Assignment preceding command name]
  a. [When the first word]
    If the TOKEN does not contain the character ’=’, rule 1 is applied. 
    Otherwise, 7b shall be applied.
  b. [Not the first word]
    If the TOKEN contains the equal sign character:
      — If it begins with ’=’, the token WORD shall be returned.
      — If all the characters preceding ’=’ form a valid name (see XBD Section 3.229, |
        on page 65), the token ASSIGNMENT_WORD shall be returned. (Quoted
        characters cannot participate in forming a valid name.)
      — Otherwise, it is unspecified whether it is ASSIGNMENT_WORD or WORD
        that is returned.
  Assignment to the NAME shall occur as specified in Section 2.9.1 (on page 2263).

由于变量名称包含无效字符,因此它不会尝试赋值,而是将其视为简单命令。

相关内容