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 task.sh with the content below which will be the nested script which will be called from another script:

# task.sh
echo "Task script was invoked!"

Running in the same process

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

# caller.sh
# run it in process using source
source ./task.sh

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

Ensure to set execute permission for the scripts before running it using chmod +x task.sh caller.sh.

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 task.sh in a different process use `./task.sh`

# caller.sh
# run it in a different process
./task.sh

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.