I want to source a file eg name.sh from another script and check the return code and decide on it's error code. If I use
source name.sh
then if name.sh return non-zero return code my main script stop to run but I need to decide on exit code weather to continue or stop.
If I use
ret_code="`source name.sh`"
echo $ret_code
then ret_code is null and no error code is printed. I can't use these:
sh name.sh
./name.sh
bash name.sh
because name.sh is not executable and I don't want it to be executable
The construct var=$(myfunction) captures the standard out from myfunction and saves it in var . Thus, when you want to return something from myfunction , just send it to standard, like we did with echo in the example above.
Functions can return values using any one of the three methods: #1) Change the state of a variable or variables. #2) Use the return command to end the function and return the supplied value to the calling section of the shell script. Running the function with a single parameter will echo the value.
${} Parameter Substitution/Expansion A parameter, in Bash, is an entity that is used to store values. A parameter can be referenced by a number, a name, or by a special symbol.
File does not need to be executable to run sh name.sh
. Than use $?
.
sh name.sh
ret_code=$?
The return code should be in the variable $?
. You can do the following:
source name.sh # Execute shell script
ret_code=$? # Capture return code
echo $ret_code
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With