I use bash functions which are in different script files.
Theses scripts function files are sourced when necessary.
As function does not easily return string value, Value are return using the echo function, and a return code is returned..
Now here my question :
In the main script I want to get the error code which is 0 if every things run correctly, otherwise it is different from 0.
As in my example "function2 return always 2, I expect an error code different from 0.
But I always get 0 ( success ).
I suppose because the last function in the pipe (not_important_function_b) always success and then set the return code to 0. Even if the first part of the pipe failed.
If the last part of a pipe return no error and if a previous part of a pipe return one error, how to get the error code for the global result which must be considered as failing.
PS:
In your main script, maybe you could try something like:
if MY_DATA=$(function_1 "param1" "param2" "param3")
then echo "yay : $MY_DATA"
else err=$?
echo "no : $err"
fi
hth
EDIT:
Your "typos" include beeing on the wrong line?
gee use the real one or care more about the example representing properly your question with working example... like... many of your code looks almost like incomplete csh, rather than bash.
If the last part of a pipe return no error and if a previous part of a pipe return one error (say 123)
1�) What is the value of $RETURN_CODE 0 or 123
2�) Is the return code set to 0 ( if not, I have a problem somewhere in my code)
how to get the error code (123) for the global result which must be considered as failing.
If function2 FAILS, as in a code typo or floating number exception, then the pipe will be ignored and therefor the RETURN_CODE is the exception number of function2.
However, if function2 'ends' properly with an exit number, whatever comes out (or not) stdout will be passed to not_important_function_b which therfor will 'overwrite' the previous return value $? of function2, by its own value - as you report - 0.
with any other Bourne like shells
You need to use a trick to pass the exit codes to the main
shell. You can do it using a pipe(2). Instead of running
"cmd1", you run "cmd1; echo $?" and make sure $? makes it way
to the shell.
exec 3>&1
eval `
# now, inside the `...`, fd4 goes to the pipe
# whose other end is read and passed to eval;
# fd1 is the normal standard output preserved
# the line before with exec 3>&1
exec 4>&1 >&3 3>&-
{
cmd1 4>&-; echo "ec1=$?;" >&4
} | {
cmd2 4>&-; echo "ec2=$?;" >&4
} | cmd3
echo "ec3=$?;" >&4
`