bash行解釋過程

bash行解釋過程

我想了解 bash 執行行解釋的確切過程。

來自 GNU bash 參考手冊:

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 (see Shell Expansions). 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 (see Redirections).

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 variable.

If no command name results, the variable assignments affect the current shell environment. Otherwise, the variables are added to the environment of the executed command and do not affect the current shell environment. 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 expansions 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.

現在讓我們舉一個簡單的例子:

var="hello friend"

echo ${var}s > log.txt

現在會發生什麼事?

根據參考, var 賦值 (1) 將在擴展 (4) 之後進行,但是 shell 如何在不先執行變數賦值的情況下擴展 var 呢?

我不知道這是我在這裡錯過的東西還是只是對手冊的誤解。

如果您能為我提供更多範例以供進一步理解,我將不勝感激。

謝謝

答案1

...擴展、分配和重定向,從左到右。

手冊上確實有不是提到它也解析自從上到下,一行接著一行。它只談論簡單的指令

你隨時可以改變

cmd1
cmd2

進入

cmd1; cmd2

但正常情況下

com ma nd 1
co mma nd 2

被人類優先選擇

com ma nd 1; co mma nd 2

在 bash 中你沒有=vs. ==,所以它需要這個特殊的語法作業重定向也提到了,這些你可以放在任何地方:

> log.txt echo ${var}s 
echo ${var}s>log.txt

線路延續反之亦然:

com \
mand 1

答案2

您有 2 個簡單的語句,每行 1 個。所以對於第一行步驟1,2和3什麼都不做,然後步驟4就是變數賦值。

對於第二行,變數在步驟 1 中展開。

答案3

這不是同一條線。 shell 將執行這些步驟兩次。

另外請注意這些:

var="hello friend"; echo ${var}s > log.txt

也是兩個簡單的指令。但是這個:

varr="hello friend" echo ${varr}s > log.txt

是一個簡單的指令。在這種情況下,您的疑問適用:${varr}將擴展為一個空字串(除非它是之前分配的;我故意使用了一個新名稱,所以舊的分配不會幹擾)。

相關內容