1

Do shell functions and aliases fork child processes? Or are they both executed within the shell process?

4

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" )
      }
  • 1
    Or 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. – Stéphane Chazelas Jan 31 '18 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. – Stéphane Chazelas Jan 31 '18 at 16:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.