|
This morning a friend suddenly asked to web site, shell programming function Why return only integer, how can the implementation of the results returned by the function and saved to a variable. Actually, this is a good solution --- just need a good understanding of the shell can function. The following is based chats finishing a few points on the function:
Several shell programming functions need to know about
First, whether it is inside a function or outside the function, the value of $ 0 is the script itself.
[Root @ target ~] # cat test.sh
#! / Bin / bash
echo $ 0
function testFunc () {
echo "In function:"
echo "\ $ 0 = $ 0"
echo "\ $ 1 = $ 1"
}
testFunc 'test test'
[Root @ target ~] # bash test.sh
test.sh
In function:
$ 0 = test.sh
$ 1 = test test
Second, the variables in the function definition (if it is not necessary to modify the global variables used) to make use of local keyword defined as a local variable, so as not to override the global value of the variable
[Root @ target ~] # 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 "\ $ TESTDATA1 = $ TESTDATA1"
}
#call function
localFunc
echo "Out of function:"
echo "\ $ TESTDATA = $ TESTDATA"
echo "\ $ TESTDATA1 = $ TESTDATA1"
[Root @ target ~] # bash local.sh
In function:
$ TESTDATA = Hello python.
$ TESTDATA1 = Hello PHP.
Out of function:
$ TESTDATA = Hello python.
$ TESTDATA1 = Hello shell.
Third, the use of the function return keyword returns a value of 0-255, indicates that the function exit status code (that is, whether the function is executed successfully), 0 on success, nonzero means failure. In their daily work, you can make the function returns whether they were successful according to the conditions for making a judgment about the use of other programs. If desired function returns a result value, and stores it in a variable, use echo statements.
[Root @ target ~] # cat return.sh
#! / Bin / bash
function returnFunc () {
echo "value"
return 247
}
DATA = $ (returnFunc)
echo "\ $? = $?"
echo "\ $ DATA = $ DATA"
[Root @ target ~] # bash return.sh
$? = 247
$ DATA = value
Fourth, if you have more than one shell script, a script needs to call another script function, you need to execute the following command to load the specified script file:
. ./func.sh
or
source ./func.sh
The operation is similar to the top include the operation of other languages.
[Root @ target ~] # cat func.sh
#! / Bin / bash
function func1 () {
echo "This is func1"
}
function func2 () {
echo "This is func2"
}
function func3 () {
echo "This is func3"
}
[Root @ target ~] # cat call.sh
#! / Bin / bash
#source ./func.sh
. ./func.sh
func1
func2
func3
[Root @ target ~] # bash call.sh
This is func1
This is func2
This is func3 |
|
|
|