процесс интерпретации строки 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), но как оболочка может расширить переменную, не выполнив сначала присвоение переменной?

Не знаю, то ли я что-то упустил, то ли просто неправильно понял руководство.

Я буду признателен, если вы сможете привести мне дополнительные примеры для дальнейшего понимания.

Спасибо

решение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

Это не та же самая строка. Оболочка выполнит эти шаги дважды.

Кроме того, обратите внимание, что:

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

также две простые команды. Но это:

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

это одна простая команда.В этом случае ваши сомнения применимы: ${varr}расширится до пустой строки (если только она не была назначена ранее; я намеренно использовал новое имя, чтобы старое назначение не мешало).

Связанный контент