I am having two shell scripts, say script1.sh and script2.sh. I am calling script2.sh from script1.sh. In script2.sh a few evaluations are done and based the results a flag is being set. Now i need to pass the flag to script1.sh based on which it will be decided whether the script1.sh should continue it execution or exit. I am not using functions. and while i export the flag, in script1.sh it is blank.
My question now is how do i return the flag from script2.sh ?
Any help ? Any Ideas? Experiences to share?
3 Answers
You could print the result and capture it in script1:
# Script 1
flag="$(./script2.bash)"
And:
# Script 2
[...]
printf '%s\n' "$flag"
Hope this helps =)
-
I would prefer this solution. Keep in mind that a non-zero exit status typically indicates an error;
script2.bash
may have have several different non-error conditions that result in distinct flag values forscript1.bash
.– chepnerCommented Oct 17, 2012 at 14:39 -
Do you know the solution to return multiple values instead of one?– AmirCommented Aug 14, 2016 at 23:08
-
I usually return them together as one value, separated by a delimiter that's not present in the variables. Then I use
cut
to separate the return value into multiple values. So, on Script 2 I'd do something like:printf '%s,%s\n' "$var1" "$var2"
(notice the,
delimeter inside theprintf
format string). Then on Script 1 I'd do:single_value="$(./script1.bash)"
followed byvar1="$(echo "$single_value" | cut -f1 -d',')"
andvar2="$(echo $single_value" | cut -f2 -d',')"
. The-d
specifies the delimiter (in this case,,
), and the-f
specifies which field. Hope this helps =) Commented Aug 20, 2016 at 15:33
Just use the exit status of script2:
if script2.sh ; then
echo Exited with zero value
else
echo Exited with non zero
fi
Use exit 0
or exit 1
in script2 to set the flag.
I would expect you to use the return code from script2.sh
(se by the statement exit {value}
)
e.g.
./script2.sh
$?
contains the return value from script2.sh
's exit statement.
You can't use export
here. export
makes the variable available to subsequent subprocesses. It can't be used to communicate a value back to a parent process, since you're modifying a copy of the variable particular to the subprocess.