How can I use && with my own functions?
Running this prints out both statements
#!开发者_高级运维/bin/bash
echo "Hello" && echo "World"
However, running this only prints out "Hello"
#!/bin/bash
message() {
echo "Hello"
return 1
}
message && echo "World"
Why doesn't this work and how can I change my script so that it does?
An "exit" value of 0 means success while anything else means failure. and the && operator doesn't execute the right hand side if the left hand side fails (that is if it returns non-zero)
So change the return 1
to return 0
return 1
(or anything else which is not 0) means false
to bash, which means the second command will not be called.
Use return 0
(this means true
), or chain them using other operators (like ||
or ;
.)
As mentioned in a comment, technically bash doesn't have boolean values, and &&
and ||
are not described as "boolean short-circuit operators" in the manual, but "control operators". As a && b
means "run b
if and only if a
succeeded", and "success" is defined as a zero exit code (and the command true
always returns 0, while false
returns 1), the net effect is the same as what I described above.
In bash a return value of 1
indicates an error.
Try return 0
&& executes the second instruction only if the first one is successful, i.e. has a 0 result
Remove the return statement in your message()
function.
精彩评论