So in bash function, I run multiple commands or functions, and I'd like to return a value that is a combination of each of the status of the commands or functions, but this doesn't seem to work, it is always the status of the 1st command. How can I fix this?
function my_func {
command_1
local result_1=$?
command_2
local result_2=$?
......
return $result_1 && $result_2 # <=== this does not work, it seems ignore result_2
}
CodePudding user response:
In shell you can only return a single integer, 0
means success, anything else is a failure. If we generate a truth table of your commands:
command_1 | command_2 | |
---|---|---|
1 | true | true |
2 | true | false |
3 | false | true |
3 | false | false |
What would be the return value you want in each case? Presumably you would wand to return success only when both commands succeed, but if that's the case there's no point in running command_2
if command_1
failed.
If this is the case, in shell all you do is:
command_1 && command_2
CodePudding user response:
Yes, you discovered it! Unlike other programming languages, bash functions and programs can only return a single integer between 0 and 255.
That's it. Not sure what else to say. We have to get a bit creative with our code!