在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 教程/ Linux/ Shell 函數(shù):Shell 函數(shù)返回值、刪除函數(shù)、在終端調(diào)用函數(shù)
Shell 特殊變量:Shell $0, $#, $*, $@, $?, $$和命令行參數(shù)
Shell 文件包含
Shell 輸入輸出重定向:Shell Here Document,/dev/null
Shell 函數(shù)參數(shù)
Shell 簡介
Shell printf命令:格式化輸出語句
第一個 Shell 腳本
Shell echo 命令
Shell 運算符:Shell 算數(shù)運算符、關(guān)系運算符、布爾運算符、字符串運算符等
Shell 數(shù)組:shell 數(shù)組的定義、數(shù)組長度
Shell until 循環(huán)
Shell if else 語句
Shell 變量:Shell 變量的定義、刪除變量、只讀變量、變量類型
Shell 字符串
Shell 與編譯型語言的差異
Shell 函數(shù):Shell 函數(shù)返回值、刪除函數(shù)、在終端調(diào)用函數(shù)
Shell 替換
Shell case esac 語句
Shell for 循環(huán)
什么時候使用 Shell
Shell 注釋
幾種常見的 Shell
Shell while 循環(huán)
Shell break 和 continue 命令

Shell 函數(shù):Shell 函數(shù)返回值、刪除函數(shù)、在終端調(diào)用函數(shù)

函數(shù)可以讓我們將一個復(fù)雜功能劃分成若干模塊,讓程序結(jié)構(gòu)更加清晰,代碼重復(fù)利用率更高。像其他編程語言一樣,Shell 也支持函數(shù)。Shell 函數(shù)必須先定義后使用。

Shell 函數(shù)的定義格式如下:

function_name () {
    list of commands
    [ return value ]
}

如果你愿意,也可以在函數(shù)名前加上關(guān)鍵字 function:

function function_name () {
    list of commands
    [ return value ]
}

函數(shù)返回值,可以顯式增加 return 語句;如果不加,會將最后一條命令運行結(jié)果作為返回值。

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

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

先來看一個例子:

#!/bin/bash

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

# Invoke your function
Hello

運行結(jié)果:

$./test.sh
Hello World
$

調(diào)用函數(shù)只需要給出函數(shù)名,不需要加括號。

再來看一個帶有 return 語句的函數(shù):

#!/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 !"

運行結(jié)果:

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 !

函數(shù)返回值在調(diào)用該函數(shù)后通過 $? 來獲得。

再來看一個函數(shù)嵌套的例子:

#!/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

運行結(jié)果:

Url_1 is http://see.xidian.edu.cn/cpp/shell/
Url_2 is http://see.xidian.edu.cn/cpp/u/xitong/

像刪除變量一樣,刪除函數(shù)也可以使用 unset 命令,不過要加上 .f 選項,如下所示:

$unset .f function_name

如果你希望直接從終端調(diào)用函數(shù),可以將函數(shù)定義在主目錄下的 .profile 文件,這樣每次登錄后,在命令提示符后面輸入函數(shù)名字就可以立即調(diào)用。