为什么变量赋值中的空格在Bash中出错?

Sai*_*ran 5 variables bash variable-assignment

#!/bin/bash

declare -r NUM1=5
NUM2 =4                # Line 4

num3=$((NUM1 + NUM2))
num4=$((NUM1 - NUM2))
num5=$((NUM1 * NUM2))
num6=$((NUM1 / NUM2))  # Line 9

echo "$num3"
echo $((5**2))
echo $((5%4)) 
Run Code Online (Sandbox Code Playgroud)

我正在使用这个bash脚本,当我运行脚本时,我收到了错误

./bash_help 
./bash_help: line 4: NUM2: command not found
./bash_help: line 9: NUM1 / NUM2: division by 0 (error token is "NUM2")
5
25
1
Run Code Online (Sandbox Code Playgroud)

所以我已将代码更改为此,错误消失了.

#!/bin/bash

declare -r NUM1=5
NUM2=4

num3=$((NUM1 + NUM2))
num4=$((NUM1 - NUM2))
num5=$((NUM1 * NUM2))
num6=$((NUM1 / NUM2))

echo "$num3"
echo $((5**2))
echo $((5%4)) 
Run Code Online (Sandbox Code Playgroud)

为变量赋值时,为什么我们不能使用空格?通常使用空格来提高代码的可读性.有谁能解释一下?

Cha*_*ffy 13

它不是bash中的约定(或者更常见的是POSIX-family shell).

至于"为什么",那是因为做错的各种方式都具有作为命令的有效含义.如果你做了NUM2 = 4一个作业,那么你就不能=在没有引用它的情况下作为文字参数传递.因此,任何此类更改都是向后兼容的,而不是放在未定义的空间中(POSIX sh标准的扩展需要生存以避免违反该标准).

NUM2= 4 # runs "4" as a command, with the environment variable NUM2 set to an empty string
NUM2 =4 # runs "NUM2" as a command, with "=4" as its argument
NUM2 = 4 # runs "NUM2" as a command, with "=" as its first argument, and "4" as another
Run Code Online (Sandbox Code Playgroud)