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) 후에 발생하지만 변수 할당을 먼저 수행하지 않고 쉘이 어떻게 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,2,3단계에서는 아무 작업도 수행하지 않으며 4단계는 변수 할당입니다.

두 번째 줄의 경우 변수는 1단계에서 확장됩니다.

답변3

같은 라인이 아니네요. 쉘은 이 단계를 두 번 수행합니다.

추가적으로 다음 사항에 유의하세요.

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

두 가지 간단한 명령도 있습니다. 하지만 이것은:

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

하나의 간단한 명령입니다.이 경우 귀하의 의심이 적용됩니다: ${varr}빈 문자열로 확장됩니다(이전에 할당되지 않은 한; 의도적으로 새 이름을 사용했기 때문에 이전 할당이 방해하지 않습니다).

관련 정보