为什么变量分配中的空格会导致Bash错误? [英] Why does a space in a variable assignment give an error in Bash?
问题描述
#!/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))
我正在使用此bash脚本,当我运行该脚本时,出现了错误
I am using this bash script, and when I was running the script, I got the error
./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
所以我将代码更改为此,错误消失了.
So I have changed the code to this and the error was gone.
#!/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))
为什么在给变量赋值时不能使用空格?习惯上使用空格以提高代码的可读性.谁能解释一下?
Why can't we use spaces when we assign a value to a variable? It is convention to use spaces for better readability of the code. Can anyone explain this?
推荐答案
这不是bash中的约定(或更常见的是POSIX系列shell).
It's not a convention in bash (or, more generally, POSIX-family shells).
至于为什么",这是因为各种错误的处理方式都具有作为命令的有效含义.如果对NUM2 = 4
进行了赋值,则无法在不加引号的情况下将=
作为文字参数传递. 因此,任何此类更改都将是向后不兼容的,而不是将其放置在未定义的空间中(需要保留POSIX sh标准的扩展,以避免构成对该标准的违反).
As for "why", that's because the various ways of doing it wrong all have valid meanings as commands. If you made NUM2 = 4
an assignment, then you couldn't pass =
as a literal argument without quoting it. Consequently, any such change would be backwards-incompatible, rather than being placed in undefined space (where extensions to the POSIX sh standard need to live to avoid constituting violations of that standard).
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
这篇关于为什么变量分配中的空格会导致Bash错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!