Function 可以有两种写法:
function_name () {
<commands>
}
or
function function_name {
<commands>
}
[@entmcnode15] try $ cat arguments.sh
#!/bin/bash
# Passing arguments to a function
print_something () {
echo Hello $1
echo second is $2
}
print_something Mars Lukas
print_something Jupiter Lando
[@entmcnode15] try $ ./arguments.sh
Hello Mars
second is Lukas
Hello Jupiter
second is Lando
[@entmcnode15] try $
解释:
print_something Mars Lukas
直接调用函数名,后面跟的两个参数分别作为$1与$2传入函数。
Return Values
在bash函数中, use the keyword return to indicate a return status.
[@entmcnode15] try $ ./arguments.sh
Hello Mars
second is Lukas
Hello Jupiter
second is Lando
The previous function has a return value of 5
[@entmcnode15] try $ cat arguments.sh
#!/bin/bash
# Passing arguments to a function
print_something () {
echo Hello $1
echo second is $2
return 5
}
print_something Mars Lukas
print_something Jupiter Lando
echo The previous function has a return value of $?
[@entmcnode15] try $
<span style="background-color: rgb(255, 255, 255);">$?为上一轮命令执行的return status,return value是5</span>
Variable Scope
默认情况下 variable is global, 在其所在的script中可见;若在函数中将变量定义为local,则只在此函数中可见,用关键字local,local var_name=<var_value>
<pre name="code" class="cpp">[@entmcnode15] try $ ./function.sh
Before function call: var1 is global 1 : var2 is global 2
Inside function: var1 is local 1 : var2 is global 2
Inside function,modify value: var1 is changed again : var2 is 2 changed again
After function call: var1 is global 1 : var2 is 2 changed again
[@entmcnode15] try $ cat function.sh
#!/bin/bash
# Experimenting with variable scope
var1='global 1'
var2='global 2'
echo Before function call: var1 is $var1 : var2 is $var2
var_change () {
local var1='local 1'
echo Inside function: var1 is $var1 : var2 is $var2
var1='changed again'
var2='2 changed again'
echo Inside function,modify value: var1 is $var1 : var2 is $var2
}
var_change
echo After function call: var1 is $var1 : var2 is $var2
Overriding Commands
我们可以将我们的函数命名成与已有的命令同名,这样就可以对命令进行重写。但注意在函数中调用同名命令时需要加上command ,否则就会进入死循环。
[@entmcnode15] try $ cat overwrite.sh
#!/bin/bash
echo(){
command echo override echo
}
echo
[@entmcnode15] try $ ./overwrite.sh
override echo
注意:
command echo override echo
前要加command,否则echo函数一直调用自身,进入死循环。
Summary
-
function <name> or <name> ()
- Create a function called name. return <value>
- Exit the function with a return status of value. local <name>=<value>
- Create a local variable within a function. command <command>
- Run the command with that name as opposed to the function with the same name.