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

今、何が起きた?

参照によれば、変数の割り当て(1)は展開(4)の後に行われますが、シェルは最初に変数の割り当てを実行せずにどのようにして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

1 行に 1 つずつ、2 つの簡単なステートメントがあります。したがって、最初の行のステップ 1、2、3 は何も実行せず、ステップ 4 は変数の割り当てです。

2 行目では、ステップ 1 で変数が展開されます。

答え3

同じ行ではありません。シェルはこれらの手順を 2 回実行します。

さらに、次の点に注意してください。

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

2つの簡単なコマンドもあります。しかし、これは:

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

は 1 つの簡単なコマンドです。この場合、あなたの疑問は当てはまる:${varr}は空の文字列に展開されます (以前に割り当てられていない限り。意図的に新しい名前を使用したので、古い割り当ては影響しません)。

関連情報