Shell function return value, two common methods:Return,Echo
1) Return Statement
The Return Value of the shell function, which can be the same as that of other languages, returned through the return statement.
Example:
#!/bin/sh function test() { echo "arg1 = $1" if [ $1 = "1" ] ;then return 1 else return 0 fi } echo echo "test 1" test 1 echo $? # print return result echo echo "test 0" test 0 echo $? # print return result echo echo "test 2" test 2 echo $? # print return result
Output result:
Test 1
Arg1 = 1
1
Test 0
Arg1 = 0
0
Test 2
Arg1 = 2
0
First, a function test is defined to return 1 or return 0 based on whether the input parameter is 1.
Obtain the return value of a function by calling the function or the value of the last execution.
In addition, the return value of the function can be directly used as the if judgment.
Note: return can only be used to return an integer. The difference between return and C is that return is correct, and other values are incorrect.
3) echo Return Value
In shell, the return value of a function has a very safe return method, that is, it is returned by outputting to the standard output. Because the child process inherits the standard output of the parent process, the output of the child process is directly reflected to the parent process.
Example:
#!/bin/sh function test() { echo "arg1 = $1" if [ $1 = "1" ] ;then echo "1" else echo "0" fi } echo echo "test 1" test 1 echo echo "test 0" test 0 echo echo "test 2" test 2
Result:
Test 1
Arg1 = 1
1
Test 0
Arg1 = 0
0
Test 2
Arg1 = 2
0
Why? Are there any mistakes? there is almost no difference between the two functions. Yes, it is almost the same as return and ECHO, but there are 1.1 things to note that they cannot output something that is not the result to the standard (that is, do not echo unnecessary information), such as debugging information, which can be redirected to a file. Note that, when using other commands such as grep in the script, you must remember that 1>/dev/null 2> & 1 to empty the output information and output it to a null device, avoid the output of these commands.