How to call one shell script from another shell script?
I have two shell scripts,
How can I call
b.sh from within the shell script
There are a couple of different ways you can do this:
Make the other script executable, add the
#!/bin/bashline 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
sourcecommand (alias is
.) like this:
Or use the
bashcommand to execute it:
The first and third methods execute the script as another process, so variables and functions in the other script will not be accessible.
The second method 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.
Read more… Read less…
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."
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!!!
The answer which I was looking for:
( exec "path/to/script" )
exec replaces the shell without creating a new process. However, we can put it in a subshell, which is done using the parantheses.
( "path/to/script" ) is enough.
If you want load variables on current console and execute you may use
source myshellfile.sh on your code. Example:
!#/bin/bash set -x echo "This is an example of run another INTO this session." source my_lib_of_variables_and_functions.sh echo "The function internal_function() is defined into my lib." returned_value=internal_function() echo $this_is_an_internal_variable set +x
If you just want to execute a file and the only thing intersting for you is the result, you can do:
!#/bin/bash set -x ./executing_only.sh sh i_can_execute_this_way_too.sh bash or_this_way.sh set +x
I hope helps you. Thanks.
You can use
/bin/sh to call or execute another script (via your actual script):
# cat showdate.sh #!/bin/bash echo "Date is: `date`" # cat mainscript.sh #!/bin/bash echo "You are login as: `whoami`" echo "`/bin/sh ./showdate.sh`" # exact path for the script file
The output would be:
# ./mainscript.sh You are login as: root Date is: Thu Oct 17 02:56:36 EDT 2013