为什么变量赋值中的空格会在 Bash 中出错? [英] Why does a space in a variable assignment give an error in Bash?

查看:24
本文介绍了为什么变量赋值中的空格会在 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆