变量名可以包含`-`吗?

Tim*_*Tim 1 bash

$ my-num=1
my-num=1: command not found

$ mynum=1
Run Code Online (Sandbox Code Playgroud)

我想知道为什么第一个任务失败了?

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

-在bash一些特殊字符?

谢谢。

jes*_*e_b 8

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.
Run Code Online (Sandbox Code Playgroud)

在 Shell Grammar Rules 的 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).
Run Code Online (Sandbox Code Playgroud)

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

  • @Tim:*还能是什么*?它是命令行中的第一个单词;所以它要么是一个别名(它不是,shell 检查了),要么是一个函数(它不是,shell 检查了),或者是一个内部命令(它不是,shell 检查了)。所以它必须是一个可执行文件的名称。shell 在 `$PATH` 的目录中寻找它,并没有找到它。所以它说“找不到命令”。 (3认同)