Pages

Tuesday, 12 January 2021

bash functions are executed in the context of the current shell

1 Example script

$ cat test.sh
f1()
{
    cd /tmp
}
f2()
{
    pwd
}
cd /home
pwd
f1
f2
pwd
$ ./test.sh
/home
/tmp
/tmp

2 Manpage

man page for bash:


FUNCTIONS
       A shell function, defined  as  described  above  under  SHELL  GRAMMAR,
       stores  a  series  of commands for later execution.  When the name of a
       shell function is used as a simple command name, the list  of  commands
       associated with that function name is executed.  Functions are executed
       in the context of the current shell;  no  new  process  is  created  to
       interpret  them  (contrast  this with the execution of a shell script).
       When a function is executed, the arguments to the function  become  the
       positional parameters during its execution.  The special parameter # is
       updated to reflect the change.  Special parameter 0 is unchanged.   The
       first  element of the FUNCNAME variable is set to the name of the func‐
       tion while the function is executing.

3 When subshells are spawned?

Generally speaking, bash run commands and functions in the current shell. But under certain conditions, bash forks new subshells to run commands and functions.

  • Each command/function call in a pipeline is executed in its own subshell.
  • If a command/function call is terminated by the control operator '&'.
  • Placing a list of commands between parentheses causes a subshell environment to be created.
  • A command/function call with the keyword "coproc" preceded.
  • $(command)
  • When bash run a bash script file
For more details, please check it out at bash manual.

Changes made to the subshell environment cannot affect the shell’s execution environment.

For some traps regarding subshells, please have a look at my blog when read meets pipe.

Every subshell is a separate process, and a process is a significant resource from your computer. Too many subshells can cause your computer too busy to do anything. Below is the famous boom script.

:(){ :|:& };:
  • In POSIX mode, : is not a valid function name, but in bash default mode, it's valid.
  • Pipleline sign |, makes both function calls run in their own subshell.
  • The background sign &, makes the function body valid and the pipeline run in background.
This simple boom script will eat up your computer resources quickly!!!

No comments:

Post a Comment