In the world of Unix and Linux, shell scripting is a powerful tool for automating tasks, managing systems, and more. Often, we find ourselves needing to call one shell script from within another. This not only helps in organizing complex scripts into manageable chunks but also aids in reusability and maintenance.

Advertisement

Why Call a Script from Another Script?

  • Modularity: Breaking down complex scripts into smaller, manageable ones.
  • Reusability: Using the same script in multiple other scripts without rewriting code.
  • Organization: Easier maintenance and readability.

Basic Method

The most straightforward way to call a script from another is by using its path in the parent script.

Example:

Suppose you have two scripts: script1.sh and script2.sh.

script1.sh:


#!/bin/bash
echo "This is Script 1"

script2.sh:


#!/bin/bash
echo "Calling Script 1 from Script 2"
./script1.sh
echo "Script 1 has finished execution"

In this example, script2.sh calls script1.sh. The ./ before script1.sh assumes that both scripts are in the same directory and that script1.sh is executable (chmod +x script1.sh to make it executable).

Passing Arguments

You can also pass arguments from one script to another.

Example:

script1.sh:


#!/bin/bash
echo "Script 1 received the argument: $1"

script2.sh:


#!/bin/bash
./script1.sh "Hello from Script 2"

In this case, script2.sh passes the string “Hello from Script 2” to script1.sh, which is received as $1 (the first argument) in script1.sh.

Using Source Command

Another method is using the source command or its shorthand .. This method executes the called script in the current shell environment, which means any variables or changes made by the called script are retained in the calling script.

Example:

script1.sh:


#!/bin/bash
MESSAGE="Message from Script 1"

script2.sh:


#!/bin/bash
source ./script1.sh
echo $MESSAGE

In this example, script2.sh will output “Message from Script 1” because it retains the environment changes made by script1.sh.

Conclusion

Calling one shell script from another is a fundamental technique in shell scripting. It enhances the script’s modularity, reusability, and organization. Whether you’re a system administrator, developer, or just a Linux enthusiast, mastering this technique is essential for efficient scripting.

Share.
Leave A Reply


Exit mobile version