Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

source a shell script from another script and check return code

Tags:

bash

shell

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

like image 722
amin Avatar asked May 21 '13 11:05

amin


People also ask

How do I return a value from one shell script to another shell?

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.

Can a shell script return value?

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.

What is ${} in shell script?

${} 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.


2 Answers

File does not need to be executable to run sh name.sh. Than use $?.

sh name.sh
ret_code=$?
like image 150
Grzegorz Żur Avatar answered Nov 14 '22 08:11

Grzegorz Żur


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
like image 44
unxnut Avatar answered Nov 14 '22 08:11

unxnut