Shell: How to call one shell script from another shell script?
Solution 1:
There are a couple of different ways you can do this:
-
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; -
Or call it with the
source
command (alias is.
), like this:source /path/to/script
-
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.
Solution 2:
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."
Solution 3:
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!!!
Solution 4:
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.