How do I call an other shell script and wait for its completion?
I want to pass input arguments and receive returning result code. And continue running rest of codes.
3 Answers 3
You don't say which shell you're using, so assuming bash, you just do
#!/bin/bash
/path/to/other/script arg1 arg2
rc=$?
The variable rc now contains the return code from your other script. Depending on what you're trying to achieve, you might try and do more stuff, but your question is so vague, that's the best starting point.
Depending on what you're trying to do, there are two main possibilities:
You can call the other script like you would call any other program.
/path/to/other/script foo bar echo "The script exited with status $?"
You can "source" the other script, i.e. have the running shell read it and execute its contents. This way the called script (the variable assignments, current directory changes, etc.) modifies its caller's environment. The built-in to source another script is called
.
(just a dot); some shells havesource
as another name for.
. You can't pass arguments that way (well, you can in some shells but not all); but the called script has access to all of the caller's variables.. /path/to/other/script
Either way, if you omit the path to the other script, it'll be looked up in $PATH
. Some shells automatically look in the current directory as well, but others don't (the standard behavior is not to).
-
Sourcing a script with . or source will cause the main script to exit prematurely if the sourced script executes an exit statement.... Aside from that, wrapping the source script command in a function definition would allow passing of parameters to it... (but would need to change occurrences of 'exit' to 'return') ... That's the case in my bash test..Peter.O– Peter.O2011年06月25日 21:33:17 +00:00Commented Jun 25, 2011 at 21:33
Yet another way to do this exists.
If you use the real Korn Shell (not sure about pdksh) you can have dynamically loaded functions.
Create file named "main" somewhere in PATH:
#!/bin/ksh
echo "Main ksh script"
echo "Calling georgi, probably in another file"
georgi 1ドル 2ドル 3ドル
echo "Back from georgi"
franco 1ドル 2ドル 3ドル
Create file named "georgi" somewhere else, say /tmp
:
function georgi {
echo "Enter function georgi 1ドル 2ドル 3ドル"
}
function franco {
echo "Enter function franco 1ドル 2ドル 3ドル"
}
Make file main executable. Make file "georgi" not execuable. Export a variable named FPATH:
export FPATH=/tmp
Run file "main":
% ./main aaa bbb c123
Main ksh script
Calling georgi, probably in another file
Enter function georgi aaa bbb c123
Back from georgi
Enter function franco aaa bbb c123
This is sort of obscure, and you have to get things exactly correct, like naming the autoloaded file the same as the first function in it that you call, and not having the autoloaded file marked executable if it's in PATH and FPATH.