Do shell functions and aliases fork child processes? Or are they both executed within the shell process?
1 Answer
No.
An alias is a simple substitution of one (or more) words for some string before the line is parsed to tokens. There is no shell context change needed.
From bash manual on Shell Functions:
Shell functions are executed in the current shell context; no new process is created to interpret them.
Unless the code that compose the function does fork a subprocess, like in bash with (…)
(not in ksh). A function could be defined with parenthesis instead of (or additionally to) curly braces.
Test:
#!/bin/bash
func(){ echo "$BASHPID"; }
fork()( echo "$BASHPID"; )
echo "$BASHPID"
func
fork
On execution:
$ ./script
8731
8731
8753
Understand the fork function as:
fork(){
( echo "BASHPID" )
}
-
1Or more to the point, a function is just giving a name to a command (though in
bash
contrary to most other Bourne-like shells), it's limited to compound commands (including, but not limited to(...)
and{...;}
). Invoking the function is like invoking the corresponding compound command (with the added benefits that you can pass arguments that will be available as$1
,$2
... in the command and with some shells have local scope for variables or options inside). So if the command forks a subshell, that will fork a subshell and if not, not. Commented Jan 31, 2018 at 16:12 -
Note that subshell and forking a child process are not necessarily the same thing. Most shells (including
bash
) implement subshells by forking, but they don't have to. ksh93 for instance doesn't. Commented Jan 31, 2018 at 16:15