[英]Variable assignment in command substitution
假設我們有一個命令輸出一個變量賦值字符串,比如'var = foo',如果我把這個命令放在命令替換中,看起來像$(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 ~]$
既然我們可以直接將變量賦值放在命令替換中,就像這個$(var=foo)
(盡管我認為它沒有意義),並且$(echo ls)
按預期工作, 為什么在命令替換中輸出賦值會導致錯誤?
這是關於命令替換的man bash
:
命令替換允許輸出命令來替換命令名稱。
Bash通過在子shell環境中執行命令並使用命令的標准輸出替換命令替換來執行擴展,並刪除任何尾隨換行符。
據我了解, $(echo var=foo)
應該由var=foo
替換,就像$(var=foo)
。
我弄錯了嗎?
這是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.
[...]
在您的情況下,simple命令只有一個單詞$(echo var=foo)
。
由於沒有標記為變量賦值的單詞(因為該單詞是命令替換),因此步驟1不適用。
然后我們繼續前進到第2步,其中單詞$(echo var=foo)
被擴展為var=foo
。 我們不回到第一步,我們只是做第2步說:“把第一個單詞作為命令的名稱”。
這就是var=foo
作為命令執行而不是被解釋為賦值的原因。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.