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.
發佈了45 篇原創文章 · 獲贊 18 · 訪問量 14萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章