根据命令行参数变量扩展声明局部变量时,bash 中是否需要引号?

Are quotes necessary in bash when declaring local variables based on the command line argument variable expansion?

下面例子中的引号是必要的还是多余的。为什么?

#!/bin/bash

arg1=""
arg2=""

</code>为<code>123 echo abc时,第一个赋值不被解释为:

如何解释
arg1=123 echo abc

这是一个普通命令 (echo) 调用,带有参数 abc 和传递给执行的环境变量 (arg)。

来自 POSIX shell 语法规范的 section 2.9.1

Each variable assignment shall be expanded for tilde expansion, parameter expansion, command substitution, arithmetic expansion, and quote removal prior to assigning the value.

字符串拆分和通配(双引号抑制的步骤)不在此列表中。

因此,引号是多余的——不仅对于右侧和侧面指的是位置参数的赋值,而且对于 所有 赋值,除了那些 (1)需要单引号而非双引号字符串的行为;或 (2) 值中的空格或其他内容将被解析为句法而非文字。


(请注意,关于如何解析命令的决定——因此,无论它是赋值、简单命令、复合命令还是其他东西——发生在before 参数扩展;因此,var= 被确定为在 的值被考虑之前的赋值!如果这是不正确的,这样数据可以默默地成为语法,它会在 bash).

中编写处理不受信任数据的安全代码要困难得多——如果不是不可能的话