Shell: How to call one shell script from another shell script? – Dev

The best answers to the question “Shell: How to call one shell script from another shell script?” in the category Dev.

QUESTION:

I have two shell scripts, a.sh and b.sh.

How can I call b.sh from within the shell script a.sh?

ANSWER:

Check this out.

#!/bin/bash
echo "This script is about to run another script."
sh ./script.sh
echo "This script has just run another script."

ANSWER:

There are a couple of different ways you can do this:

  1. Make the other script executable, add the #!/bin/bash line at the top, and the path where the file is to the $PATH environment variable. Then you can call it as a normal command;

  2. Or call it with the source command (alias is .), like this:

    source /path/to/script
    
  3. Or use the bash command to execute it, like:

    /bin/bash /path/to/script
    

The first and third approaches execute the script as another process, so variables and functions in the other script will not be accessible.
The second approach executes the script in the first script’s process, and pulls in variables and functions from the other script (so they are usable from the calling script).

In the second method, if you are using exit in second script, it will exit the first script as well. Which will not happen in first and third methods.

ANSWER:

The answer which I was looking for:

( exec "path/to/script" )

As mentioned, exec replaces the shell without creating a new process. However, we can put it in a subshell, which is done using the parantheses.

EDIT:
Actually ( "path/to/script" ) is enough.

ANSWER:

There are a couple of ways you can do this. Terminal to execute the script:

#!/bin/bash
SCRIPT_PATH="/path/to/script.sh"

# Here you execute your script
"$SCRIPT_PATH"

# or
. "$SCRIPT_PATH"

# or
source "$SCRIPT_PATH"

# or
bash "$SCRIPT_PATH"

# or
eval '"$SCRIPT_PATH"'

# or
OUTPUT=$("$SCRIPT_PATH")
echo $OUTPUT

# or
OUTPUT=`"$SCRIPT_PATH"`
echo $OUTPUT

# or
("$SCRIPT_PATH")

# or
(exec "$SCRIPT_PATH")

All this is correct for the path with spaces!!!