bash - 为什么在同一行变量赋值后 shell 内置冒号命令 ":"会导致分配空字符串值?

标签 bash shell sh variable-assignment built-in

如果我在赋值后添加 冒号 (:) 内置 shell 命令,变量将被分配给空字符串 ("" ).为什么会这样?我预计它不会有任何影响。

    set -vx
    MyVar1='my var 1'  : colon comment here  # *** !!! This gets assigned to empty string!!!
    MyVar2='my var 2'  # hash comment here; this is fine

    echo "MyVar1 = [$MyVar1]"  # EXPECTED: 'my var 1'; ACTUAL: '' (empty string).  Why?
    echo "MyVar2 = [$MyVar2]"  # As expected.

: (a colon)
: [arguments]
Do nothing beyond expanding arguments and performing redirections. The return status is zero.
https://www.gnu.org/software/bash/manual/html_node/Bourne-Shell-Builtins.html

最佳答案

: 是一个成功返回的内置命令(true 的简写版本)。

当您在与命令相同的行上执行变量赋值时,赋值仅在命令期间有效(这通常用于运行设置了临时环境变量的命令)。

所以当你运行时:

MyVar1='my var 1'  : colon comment here

你是:

  • 运行命令:
  • 传递参​​数 coloncommenthere(这些由命令删除)
  • 使用临时变量赋值MyVar1='my var 1'(这对命令没有影响)

此行为在 the spec 中有所描述:

A "simple command" is a sequence of optional variable assignments and redirections, in any sequence, optionally followed by words and redirections, terminated by a control operator.

...

If no command name results, variable assignments shall affect the current execution environment. Otherwise, the variable assignments shall be exported for the execution environment of the command and shall not affect the current execution environment (except for special built-ins).

正如评论中指出的(谢谢!),: is one of the special built-ins ,这意味着在符合标准的 shell 中,赋值应该影响当前的执行环境。默认情况下,Bash 在这个意义上不符合规范,尽管您可以通过将它调用为 sh(在它是默认 shell 的系统上)或使用 bash --posix:

$ bash -c 'foo=bar :; echo $foo'

$ sh -c 'foo=bar :; echo $foo'
bar
$ bash --posix -c 'foo=bar :; echo $foo'
bar

关于bash - 为什么在同一行变量赋值后 shell 内置冒号命令 ":"会导致分配空字符串值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57374562/

相关文章:

java - 通过 xrdp 登录时清除 LD_LIBRARY_PATH

Linux : Send message when a user logs in

linux - 一个 liner shell 脚本,用于按日期重组文件

xml - 如何使用 bash 脚本编辑 XML?

json - JQ - 按层次结构解析字段

linux - shell 脚本: Excecute a command in "screen"

android - 使用 Android 应用程序运行脚本

c# - 编写具有远程 shell 功能的程序,如 netcat

linux - 将用户名和其他参数通过管道传递给命令行实用程序

linux - 是否可以使 wget 的进度条适应多个文件?