Functions, used in script(Linux)

Function 可以有两种写法:

function_name () {
<commands>
}

or

function function_name {
<commands>
}

在bash中,function的参数传递与c语言等不一样,在调用时是直接在函数名后面写上要传递的参数,function_name argument  argument

[@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.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值