Subprocess Vs Subshell
What’s Shell
A program provides prompt for
- Interpret command
- Execute command
Command
- Builtin (use
typeto tell) - External
SubProcess vs SubShell
SubProcess (aka child process)
- Created by parent process making system calls
forkfollowed byexec - independent of parent process
- Inherits only exported variables (e.g. env vars) from parent process
Examples: invoking a non builtin script ./myscript
Note: A sourced script is executed within the parent shell. No sub-process is created for it.
SubShell
- Is a SubProcess almost identical to parent process
- Inherits non exported variables, functions from parent as well
Examples:
- command within
(...) - command pipes
ls -la | wc
#!/bin/bash
name1="test1"
export name2="test2"
{ typeset name3="test3"} #This is a local variable. It cannot be accessed outside the braces.
(echo $name1) #This is executed in a sub-shell. Hence prints 'name1'
(echo $name2) #This is executed in a sub-shell. Hence prints 'name2'
(echo $name3) #This is executed in a sub=shell. It does not have access to the local variable 'name3'
./script2.sh #script2.sh is executed as a sub-process. Can only print 'name2'
. script2.sh #script2.sh is sourced into the current script. Can print name1, name2
source script2.sh #script2.sh is sourced into the current script. Can print name1, name2