简体   繁体   中英

how does shell run sh scripts?

We know that each time a user runs a program by typing the name of an executable object file to the shell, the shell creates(use fork ) a new process and then loads(use execve ) and runs the executable object file in the context of this new process.

Below is my understanding of how a shell works internally, please correct me if I was wrong:

Commands such as ls , cat etc are executable objects (source file written by C) are in /bin/ directory. for example, when a user type in bash shell ls to list files and directories, the bash shell inteprets ls command and fork a child process to run ls

Q1-Is my understanding correct?

Q2-if my understanding is correct, then when a shell run .sh script file which is:

#!/bin/sh
echo "what is your name?"
read name

so the shell forks two child processes for echo and read , then how does these two processes communicate with each other? I mean how does the return output of echo process get passed to read process?

Is my understanding correct?

Generally, yes. But the executable file not necessarily is in /bin/ . A file named ls is searched in paths specified inside PATH environment variable and the match is used. The file can be in /usr/bin /usr/sbin /usr/local/bin etc.

And ls may be a builtin. Or a function. Or an alias.

so the shell forks two child processes for echo and read

And this is where a "built-in" comes in. A built-in is an internal part of the shell handled internally by the shell. There is no fork , just some internal code is run and that way it can modify the environment variables. echo not necessarily is a builtin, it only outputs data. But read has to be handled specially and most probably is a builtin for it to modify name variable (there is no requirement for read to be builtin, it may not be, but usually shell writers solve this problem by just making read a builtin).

On bash you can check the type of command with type . Ex. type echo shows echo is a shell builtin .

I mean how does the return output of echo process get passed to read process?

It doesn't.

You may want to read posix Command Search and Execution .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM