Calling nested shell scripts: same process or in different process

Photo by Giulia May on Unsplash

Calling nested shell scripts: same process or in different process

In Unix-like operating systems, shell scripts can be called from within other shell scripts, either to run in the same process or in a different process. Let's explore both approaches.

Let us create a bash script named with the content below which will be the nested script which will be called from another script:

echo "Task script was invoked!"

Running in the same process

Now, let us create the script which calls the script and runs it in the same process by using source ./ or . ./

# run it in process using source
source ./

# or alternatively use the format below to run it in process
. ./

Ensure to set execute permission for the scripts before running it using chmod +x

The following are the considerations to use in-process:

  • Shared Environment: The called script can access and modify the variables and functions of the calling script. Useful for setting environment variables or modifying the state that should persist after the script finishes.

  • Efficiency: There is no overhead of starting a new shell process. Faster execution as it avoids the process creation overhead.

  • Control: The calling script has more control over the execution flow. Easier to manage and debug since everything runs in a single shell instance.

Running in the different process

To run the in a different process use `./`

# run it in a different process

The following are the considerations for running in separate/different process:

  • Isolation: The called script runs in its own independent environment. Changes made in the called script do not affect the calling script’s environment and variables.

  • Parallel Execution: Allows for parallel or background execution using & . Useful for running multiple tasks concurrently.

  • Error Containment: Errors or crashes in the called script do not directly affect the calling script. Easier to isolate and handle script failures.