Reputation: 3187
I am new to shell script and I am seeing something that I don't understand.
Consider the code below:
function test {
return 0
}
if test; then
echo "hihi"
fi
If I execute the code, it will call "hihi". If the test return 1, it will not call.
I am just wondering why?
Upvotes: 1
Views: 53
Reputation: 13709
Having a non-zero return value indicates some issue/error in Unix terminology, so if you replace the return 0 with some non-zero number you'll go into the else block
function test {
return 1 # or any non-zero value
}
if test; then
echo "hihi"
else
echo 'else block'
fi
Output:
else block
Upvotes: 1
Reputation:
In UNIX, an exit code of 0 is used to signal success, while a non-zero exit code signals some sort of error. You would read it as:
if operation_that_might_fail_succeeds; then
echo "everything went ok!"
fi
Upvotes: 3