为什么在 Shell 中可以用空格分隔多个赋值

  • 本文关键字:空格 分隔 赋值 Shell shell
  • 更新时间 :
  • 英文 :


在shell中,为什么这两个赋值可以用空格分隔?

foo="foo" bar="bar"

众所周知,用";"分隔的命令是按顺序执行的。空间呢?

它不是分离的独立命令;实际上它根本不是命令。

它只是命令行的语法:您可以在运行命令之前设置一些变量。仅为此命令设置变量。

var1=val1 var2=val2... cmd

简单命令是一系列可选的变量赋值 后跟以空格分隔的单词和重定向,并以 控制操作员。第一个单词指定命令为 执行,并作为参数零传递。其余的单词是 作为参数传递给调用的命令。

man bash简单命令扩展部分解释了语法:

SIMPLE COMMAND EXPANSION
       When  a  simple  command  is executed, the shell performs the following
       expansions, assignments, and redirections, from left to right.
       1.     The words that the parser has  marked  as  variable  assignments
              (those  preceding  the  command name) and redirections are saved
              for later processing.
       2.     The words that are not variable assignments or redirections  are
              expanded.   If  any words remain after expansion, the first word
              is taken to be the name of the command and the  remaining  words
              are the arguments.
       3.     Redirections are performed as described above under REDIRECTION.
       4.     The text after the = in each variable assignment undergoes tilde
              expansion, parameter expansion, command substitution, arithmetic
              expansion, and quote removal before being assigned to the  vari-
              able.
       If no command name results, the variable assignments affect the current
       shell environment.  Otherwise, the variables are added to the  environ-
       ment  of the executed command and do not affect the current shell envi-
       ronment.  If any of the assignments attempts to assign  a  value  to  a
       readonly  variable,  an error occurs, and the command exits with a non-
       zero status.
       If no command name results, redirections  are  performed,  but  do  not
       affect  the  current shell environment.  A redirection error causes the
       command to exit with a non-zero status.
       If there is a command name left after expansion, execution proceeds  as
       described  below.   Otherwise, the command exits.  If one of the expan-
       sions contained a command substitution, the exit status of the  command
       is  the  exit  status  of  the last command substitution performed.  If
       there were no command substitutions, the command exits with a status of
       zero.

第 1 点明确允许在命令名称之前进行多个变量赋值。

点后面的段落明确允许没有任何命令名称的分配。

相关内容