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

时间:2017-10-16 05:19:04

标签: shell

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

foo="foo" bar="bar"

众所周知,由';'分隔的命令是按顺序执行的。这个空间怎么样?

2 个答案:

答案 0 :(得分:2)

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

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

var1=val1 var2=val2... cmd
  

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

答案 1 :(得分:2)

man bash SIMPLE COMMAND EXPANSION 部分解释了语法:

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点清楚地允许在命令名称之前进行多个变量赋值。

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