Reputation: 157
Thanks for this Post it helped me a bit
returning value from called function in shell script
I have written a code like below :
File.c
i = system("/home/ubuntu/Documents/Flash_Desk_App/Project/test.sh -c");
printf("SH = %x",i);
test.sh
ONE=1
echo " Hello world "
clean()
{
CLEAN_FLAG=1
echo $ONE
return "$ONE"
}
option="${1}"
case ${option} in
-c)
echo "Cleaning"
clean
;;
*) echo "Usage"
usage
;;
esac
but when i execute my ./a.out this is the output
Hello world
Cleaning
1
SH = 0
IT ALWAYS PRINTS 0. CAN SOME ONE GUIDE ME IN SOLVING THIS. i WANT TO COLLECT THE VARIABLE VALUE RETURN BY SHELL IN MY C CODE.
Upvotes: 2
Views: 7787
Reputation: 92
The above answers should all do. Better to make sure you get the right return value with your bash script first.
# ./test.sh -c
# echo $?
1
(You can allways make changes to ONE=1) Then test it with your C code.. (don't forget to pass the return value from the (system) call to the WEXITSTATUS(i)) to get the right return value.
{
i = system("/home/ubuntu/Documents/Flash_Desk_App/Project/test.sh -c");
i = WEXITSTATUS(i);
printf("SH = %x",i);
}
Upvotes: 0
Reputation: 2063
It is because the script is exiting with return code 0 (success). The exit status of a command is updated for every command that is executed. If you want to exit with the status of the clean command, you will need to do the following in your script:
EDIT - including full code to see the exact changes:
ONE=1
echo " Hello world "
# Initialize RC
rc=0
clean()
{
CLEAN_FLAG=1
echo $ONE
return "$ONE"
}
option="${1}"
case ${option} in
-c)
echo "Cleaning"
# Run the clean command and capture the return code
clean
rc=$?
;;
*) echo "Usage"
usage
;;
esac
# Return the captured return code as our script's exit status.
exit $rc
Then it should work.
NOTE: you might get a different value in the C code (like 127) instead of 1. There is a strange mapping that takes place between shell exit codes and the return value of system calls from C.
An example executing this script from the bash shell:
$ ./test.sh -c
Hello world
Cleaning
1
$ echo $?
1
Thus, it can be executed as a system call from C and you can get the return code.
Upvotes: 3
Reputation: 70901
Besides the fact mentioned in Trenin's answer, apply the macro WEXITSTATUS
to the value returned by system()
to get the value returned by the command it executed.
From man 3 system
:
RETURN VALUE
The value returned is -1 on error (e.g., fork(2) failed), and the return status of the command otherwise. This latter return status is in the format specified in wait(2). Thus, the exit code of the command will be WEXITSTATUS(status). In case /bin/sh could not be executed, the exit status will be that of a command that does exit(127).
The lesson learned here is: RTFM
Upvotes: 1