This morning a friend suddenly QQ asked, shell programming function why return can only be an integer, how to return the execution of the function and save to a variable. In fact, this problem is very good to solve---only need to seriously understand the shell function can be.
Some things to know about functions in shell programming
One, whether inside a function or outside a function, the value of $ A is the script itself.
[email protected] ~]# cat test.sh #!/bin/bash echo $ function testFunc () {echo "in function:" echo "\$0=$0" echo "\$1=$1"} testFunc ' test test ' [[email protected] ~]# bash test.sh test.sh In function: $0=test.sh $1=test test
Variables defined within the function (if you do not have to modify global variables) try to define local variables using the local keyword to avoid overwriting global variable values
    
[[email protected] ~]# cat local.sh #!/bin/bash testdata= "Hello world." testdata1= "Hello shell." function localfunc () { testdata= "Hello python." local testdata1= "hello php." echo "In function:" echo "\ $TESTDATA = $TESTDATA" echo "\ $TESTDATA 1= $TESTDATA 1 " } #call function localfunc echo "Out Of function: " echo \ $TESTDATA = $TESTDATA" echo&nbsP; " \ $TESTDATA 1= $TESTDATA 1 " [[email protected] ~]# bash local.sh In function: $TESTDATA =hello python. $TESTDATA 1=hello php. out of function: $TESTDATA =hello python. $TESTDATA 1=hello shell.
Use the return keyword within the function to return a value of 0-255, indicating that the function exits the status code (that is, if the function succeeds), 0 indicates that the execution was successful, and not 0 indicates failure. In the daily work, the function can be returned according to the conditions of success, for other programs to judge the use. If you need a function to return a result value and store it in a variable, use the echo statement.
[[email protected] ~]# cat return.sh #!/bin/bash function Returnfunc () {echo "value" return 247 } data=$ (Returnfunc) echo "\$?=$?" echo "\ $DATA = $DATA" [[email protected] ~]# bash return.sh $?=247 $DATA =value
Iv. If you have multiple shell scripts, one script needs to invoke a function in another script, you need to execute the following command to load the specified script file into:
. ./func.sh
Or
source./func.sh
The actions above are similar to the include operations in other languages.
[[email protected] ~]# cat func.sh #!/bin/bash        FUNCTION FUNC1 () { echo "This is func1" }  FUNCTION FUNC2 () { echo "This is func2 " } function func3 () { echo "This is func3" } [[email protected] ~]# cat call.sh #!/bin/bash #source ./func.sh . ./func.sh func1 func2 func3 [[email protected] ~]# bash call.sh this is func1 this is func2 this is func3
This article is from the "Diannaowa" blog, make sure to keep this source http://diannaowa.blog.51cto.com/3219919/1702849
Some points to note about the function of shell programming