by &&, | | Understand the function return values in the shell.
I want to implement the following functions:
Write a function that determines whether a string contains only numbers, and returns the corresponding flag (yes/no);
By calling the function above, you determine whether a given string contains only numbers, and does different processing depending on the return value.
The problem arises when I let the function return 1 when it contains only numbers (want to use 1 for true), otherwise return 0.
Then through func && Operation_yes | | Operation_no. as a result, the opposite of the judging situation arises.
The reason is that my return value to the Shell function follows C/c++,python,java ... Understanding, and the right understanding is:
Bash functions, unlike functions in most programming languages does not allow you to return a value to the
caller. When a bash function ends It return value is it Status:zero for success, Non-zero for failure.
This behavior is understood by the following FUNC2 (the code below is a version that can be judged correctly, just to judge the opposite version, which is the return in FUNC2
0 and 1 can be exchanged):
#!/bin/Bash#file:demo.SH#Author: lxw#time: the- A- +func1 () {Echo "-----------123a-----------------------" [ -Z $ (Echo "123a"|sed 's/[0-9]//g')] &&Echo "All digits"||Echo "Not all digits"}func2 () {Echo "-----------123-----------------------" [ -Z $ (Echo "123"|sed 's/[0-9]//g')] && return0|| Return1# return Value:0_yes 1_no}func1Echo "func1 () returns"$?The return value of the func2# function is actually the exit state of the function.Echo "Func2 () returns"$?Func2&&Echo "All digits"||Echo "Not all digits"
So when the last statement is executed, &&,| | Depending on the execution state of the FUNC2 function, decide which part of the code to execute.
Execution Result:
-----------123a-----------------------0-----------123----------------------- 0-----------123-----------------------alldigits
Func && Operation_yes | | Operation_no (Shell)