歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> SHELL編程 >> Shell函數:Shell函數返回值、刪除函數、在終端調用函數

Shell函數:Shell函數返回值、刪除函數、在終端調用函數

日期:2017/3/3 17:16:47   编辑:SHELL編程
函數可以讓我們將一個復雜功能劃分成若干模塊,讓程序結構更加清晰,代碼重復利用率更高。像其他編程語言一樣,Shell 也支持函數。Shell 函數必須先定義後使用。

Shell 函數的定義格式如下:
function_name () {
    list of commands
    [ return value ]
}
如果你願意,也可以在函數名前加上關鍵字 function:
function function_name () {
    list of commands
    [ return value ]
}
函數返回值,可以顯式增加return語句;如果不加,會將最後一條命令運行結果作為返回值。

Shell 函數返回值只能是整數,一般用來表示函數執行成功與否,0表示成功,其他值表示失敗。如果 return 其他數據,比如一個字符串,往往會得到錯誤提示:“numeric argument required”。

如果一定要讓函數返回字符串,那麼可以先定義一個變量,用來接收函數的計算結果,腳本在需要的時候訪問這個變量來獲得函數返回值。

先來看一個例子:
#!/bin/bash

# Define your function here
Hello () {
   echo "Url is http://see.xidian.edu.cn/cpp/shell/"
}

# Invoke your function
Hello
運行結果:
$./test.sh
Hello World
$
調用函數只需要給出函數名,不需要加括號。

再來看一個帶有return語句的函數:
#!/bin/bash
funWithReturn(){
    echo "The function is to get the sum of two numbers..."
    echo -n "Input first number: "
    read aNum
    echo -n "Input another number: "
    read anotherNum
    echo "The two numbers are $aNum and $anotherNum !"
    return $(($aNum+$anotherNum))
}
funWithReturn
# Capture value returnd by last command
ret=$?
echo "The sum of two numbers is $ret !"
運行結果:
The function is to get the sum of two numbers...
Input first number: 25
Input another number: 50
The two numbers are 25 and 50 !
The sum of two numbers is 75 !
函數返回值在調用該函數後通過 $? 來獲得。

再來看一個函數嵌套的例子:
#!/bin/bash

# Calling one function from another
number_one () {
   echo "Url_1 is http://see.xidian.edu.cn/cpp/shell/"
   number_two
}

number_two () {
   echo "Url_2 is http://see.xidian.edu.cn/cpp/u/xitong/"
}

number_one
運行結果:
Url_1 is http://see.xidian.edu.cn/cpp/shell/
Url_2 is http://see.xidian.edu.cn/cpp/u/xitong/
像刪除變量一樣,刪除函數也可以使用 unset 命令,不過要加上 .f 選項,如下所示:
$unset .f function_name
如果你希望直接從終端調用函數,可以將函數定義在主目錄下的 .profile 文件,這樣每次登錄後,在命令提示符後面輸入函數名字就可以立即調用。
Copyright © Linux教程網 All Rights Reserved