命令替换中的变量赋值

z14*_*z14 4 bash

假设我们有一个命令输出一个变量赋值字符串,比如'var = foo',如果我把这个命令放在Command Substitution看起来像 $(echo var=foo),它会导致'command not found'错误.

[223212 dot@anne ~]$ var=foo
[223226 dot@anne ~]$
[223230 dot@anne ~]$ $(var=foo)
[223235 dot@anne ~]$
[223236 dot@anne ~]$ $(echo var=foo)
bash: var=foo: command not found
[223240 dot@anne ~]$
[224909 dot@anne ~]$ $(echo ls)
a    b    c   d    
[225036 dot@anne ~]$
[225110 dot@anne ~]$ $(echo $(var=foo))
[225116 dot@anne ~]$
Run Code Online (Sandbox Code Playgroud)

既然我们可以直接将变量赋值放在这样的命令替换中$(var=foo)(尽管我认为它没有意义),并且也$(echo ls)按预期工作,为什么在命令替换中输出赋值会导致错误?

这是man bash关于命令替换:

命令替换允许输出命令来替换命令名称.

Bash通过在子shell环境中执行命令并使用命令的标准输出替换命令替换来执行扩展,并删除任何尾随换行符.

据我所知,$(echo var=foo)应该是取代var=foo就像$(var=foo).

我弄错了吗?

tha*_*guy 6

这是man bash:

SIMPLE COMMAND EXPANSION
   When a simple command is executed, the shell performs the fol?
   lowing 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 redirec?
          tions are expanded.  If any words remain  after  expan?
          sion,  the  first  word  is taken to be the name of the
          command and the remaining words are the arguments.
   [...]
Run Code Online (Sandbox Code Playgroud)

在您的情况下,简单命令只有一个单词$(echo var=foo).

由于没有标记为变量赋值的单词(因为该单词是命令替换),因此步骤1不适用.

然后我们继续前进到第2步,将这个词$(echo var=foo)扩展为var=foo.我们不回到第一步,我们只是做第2步说:"把第一个单词作为命令的名称".

这就是为什么var=foo作为命令执行而不是被解释为赋值.