歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> SHELL編程 >> Shell 腳本知識回顧 (六) —— Shell 函數

Shell 腳本知識回顧 (六) —— Shell 函數

日期:2017/3/3 11:49:09   编辑:SHELL編程


一、Shell函數: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”。
如果一定要讓函數返回字符串,那麼可以先定義一個變量,用來接收函數的計算結果,腳本在需要的時候訪問這個變量來獲得函數返回值。
先來看一個例子:
[cpp] view
plain copy





#!/bin/bash
# Define your function here
Hello () {
echo "Url ishttp://see.xidian.edu.cn/cpp/shell/"
}
# Invoke your function
Hello
運行結果:
$./test.sh
Hello World
$
調用函數只需要給出函數名,不需要加括號。
再來看一個帶有return語句的函數:
[cpp] view
plain copy





#!/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 !
函數返回值在調用該函數後通過
$? 來獲得。
再來看一個函數嵌套的例子:
[cpp] view
plain copy





#!/bin/bash
# Calling one function from another
number_one () {
echo "Url_1 ishttp://see.xidian.edu.cn/cpp/shell/"
number_two
}
number_two () {
echo "Url_2 ishttp://see.xidian.edu.cn/cpp/u/xitong/"
}
number_one

運行結果
Url_1 ishttp://see.xidian.edu.cn/cpp/shell/ Url_2 is' target='_blank'>http://see.xidian.edu.cn/cpp/u/xitong/[/code] 
像刪除變量一樣,刪除函數也可以使用 unset 命令,不過要加上 .f 選項,如下所示:
[cpp] view
plain copy





$unset .f function_name
如果你希望直接從終端調用函數,可以將函數定義在主目錄下的 .profile 文件,這樣每次登錄後,在命令提示符後面輸入函數名字就可以立即調用。


二、Shell函數參數

在Shell中,調用函數時可以向其傳遞參數。在函數體內部,通過 $n 的形式來獲取參數的值,例如,$1表示第一個參數,$2表示第二個參數...
帶參數的函數示例:
[cpp] view
plain copy





#!/bin/bash
funWithParam(){
echo "The value of the first parameter is $1 !"
echo "The value of the second parameter is $2 !"
echo "The value of the tenth parameter is $10 !"
echo "The value of the tenth parameter is ${10} !"
echo "The value of the eleventh parameter is ${11} !"
echo "The amount of the parameters is $# !" # 參數個數
echo "The string of the parameters is $* !" # 傳遞給函數的所有參數
}
funWithParam 1 2 3 4 5 6 7 8 9 34 73
運行腳本:
The value of the first parameter is 1 !
The value of the second parameter is 2 !
The value of the tenth parameter is 10 !
The value of the tenth parameter is 34 !
The value of the eleventh parameter is 73 !
The amount of the parameters is 12 !
The string of the parameters is 1 2 3 4 5 6 7 8 9 34 73 !"
注意,$10 不能獲取第十個參數,獲取第十個參數需要${10}。當n>=10時,需要使用${n}來獲取參數。
另外,還有幾個特殊變量用來處理參數,前面已經提到:
特殊變量說明$#傳遞給函數的參數個數。$*顯示所有傳遞給函數的參數。$@與$*相同,但是略有區別,請查看Shell特殊變量。$?函數的返回值。


三、Shell輸入輸出重定向:Shell Here Document,/dev/null文件

Unix 命令默認從標准輸入設備(stdin)獲取輸入,將結果輸出到標准輸出設備(stdout)顯示。一般情況下,標准輸入設備就是鍵盤,標准輸出設備就是終端,即顯示器。


輸出重定向

命令的輸出不僅可以是顯示器,還可以很容易的轉移向到文件,這被稱為輸出重定向。
命令輸出重定向的語法為:
<ol class="snippet-num" ><li >$ <span class="sh_keyword" >command</span> <span class="sh_symbol" >></span> file</li></ol>

這樣,輸出到顯示器的內容就可以被重定向到文件。
例如,下面的命令在顯示器上不會看到任何輸出:
<ol class="snippet-num" ><li >$ who <span class="sh_symbol" >></span> users</li></ol>

打開 users 文件,可以看到下面的內容:
$ cat users
oko         tty01   Sep 12 07:30
ai          tty15   Sep 12 13:32
ruth        tty21   Sep 12 10:10
pat         tty24   Sep 12 13:07
steve       tty25   Sep 12 13:03
$
輸出重定向會覆蓋文件內容,請看下面的例子:
$ echo line 1 > users
$ cat users
line 1
$
如果不希望文件內容被覆蓋,可以使用
>> 追加到文件末尾,例如:
$ echo line 2 >> users
$ cat users
line 1
line 2
$


輸入重定向

和輸出重定向一樣,Unix 命令也可以從文件獲取輸入,語法為:
<ol class="snippet-num" ><li ><span class="sh_keyword" >command</span> <span class="sh_symbol" ><</span> file</li></ol>

這樣,本來需要從鍵盤獲取輸入的命令會轉移到文件讀取內容。
注意:輸出重定向是大於號(>),輸入重定向是小於號(<)。
例如,計算 users 文件中的行數,可以使用下面的命令:
$ wc -l users
2 users
$
也可以將輸入重定向到
users 文件:
$ wc -l < users
2
$
注意:上面兩個例子的結果不同:第一個例子,會輸出文件名;第二個不會,因為它僅僅知道從標准輸入讀取內容。


重定向深入講解

一般情況下,每個 Unix/Linux 命令運行時都會打開三個文件:
標准輸入文件(stdin):stdin的文件描述符為0,Unix程序默認從stdin讀取數據。
標准輸出文件(stdout):stdout 的文件描述符為1,Unix程序默認向stdout輸出數據。
標准錯誤文件(stderr):stderr的文件描述符為2,Unix程序會向stderr流中寫入錯誤信息。
默認情況下,command > file 將 stdout 重定向到 file,command < file 將stdin 重定向到 file。
如果希望 stderr 重定向到 file,可以這樣寫:
<ol class="snippet-num" ><li ><span class="sh_variable" >$command</span> <span class="sh_number" >2</span> <span class="sh_symbol" >></span> file</li></ol>

如果希望 stderr 追加到 file 文件末尾,可以這樣寫:
<ol class="snippet-num" ><li ><span class="sh_variable" >$command</span> <span class="sh_number" >2</span> <span class="sh_symbol" >>></span> file</li></ol>

2 表示標准錯誤文件(stderr)。
如果希望將 stdout 和 stderr 合並後重定向到 file,可以這樣寫:
<ol class="snippet-num" ><li ><span class="sh_variable" >$command</span> <span class="sh_symbol" >></span> file <span class="sh_number" >2</span><span class="sh_symbol" >>&</span><span class="sh_number" >1</span></li></ol>


<ol class="snippet-num" ><li ><span class="sh_variable" >$command</span> <span class="sh_symbol" >>></span> file <span class="sh_number" >2</span><span class="sh_symbol" >>&</span><span class="sh_number" >1</span></li></ol>

如果希望對 stdin 和 stdout 都重定向,可以這樣寫:
<ol class="snippet-num" ><li ><span class="sh_variable" >$command</span> <span class="sh_symbol" ><</span> file1 <span class="sh_symbol" >></span>file2</li></ol>

command 命令將 stdin 重定向到 file1,將 stdout 重定向到 file2。
全部可用的重定向命令列表
命令說明command > file將輸出重定向到 file。command < file將輸入重定向到 file。command >> file將輸出以追加的方式重定向到 file。n > file將文件描述符為 n 的文件重定向到 file。n >> file將文件描述符為 n 的文件以追加的方式重定向到 file。n >& m將輸出文件 m 和 n 合並。n <& m將輸入文件 m 和 n 合並。<< tag將開始標記 tag 和結束標記 tag 之間的內容作為輸入。


Here Document

Here Document 目前沒有統一的翻譯,這裡暫譯為”嵌入文檔“。Here Document 是 Shell 中的一種特殊的重定向方式,它的基本的形式如下:
<ol class="snippet-num" ><li ><span class="sh_keyword" >command</span> <span class="sh_symbol" ><<</span> delimiter</li><li >    document</li><li >delimiter</li></ol>

它的作用是將兩個 delimiter 之間的內容(document) 作為輸入傳遞給 command。
注意:
結尾的delimiter 一定要頂格寫,前面不能有任何字符,後面也不能有任何字符,包括空格和 tab 縮進。
開始的delimiter前後的空格會被忽略掉。
下面的例子,通過 wc -l 命令計算 document 的行數:
$wc -l << EOF
    This is a simple lookup program
    for good (and bad) restaurants
    in Cape Town.
EOF
3
$
也可以
將 Here Document 用在腳本中,例如:
[cpp] view
plain copy





#!/bin/bash
cat << EOF
This is a simple lookup program
for good (and bad) restaurants
in Cape Town.
EOF
運行結果:
This is a simple lookup program
for good (and bad) restaurants
in Cape Town.

下面的腳本通過 vi 編輯器將 document 保存到 test.txt 文件:
[cpp] view
plain copy





#!/bin/sh
filename=test.txt
vi $filename <<EndOfCommands
i
This file was created automatically from
a shell script
^[
ZZ
EndOfCommands
運行腳本:
$ sh test.sh
Vim: Warning: Input is not from a terminal
$
打開
test.txt,可以看到下面的內容:
$ cat test.txt
This file was created automatically from
a shell script
$


/dev/null 文件

如果希望執行某個命令,但又不希望在屏幕上顯示輸出結果,那麼可以將輸出重定向到 /dev/null:

<ol class="snippet-num" ><li >$ <span class="sh_keyword" >command</span> <span class="sh_symbol" >></span> <span class="sh_normal">/dev/null</span></li></ol>

/dev/null 是一個特殊的文件,寫入到它的內容都會被丟棄;如果嘗試從該文件讀取內容,那麼什麼也讀不到。但是 /dev/null
文件非常有用,將命令的輸出重定向到它,會起到”禁止輸出“的效果。
如果希望屏蔽 stdout 和 stderr,可以這樣寫:
<ol class="snippet-num" ><li >$ <span class="sh_keyword" >command</span> <span class="sh_symbol" >></span> <span class="sh_normal">/dev/null</span> <span class="sh_number" >2</span><span class="sh_symbol" >>&</span><span class="sh_number" >1</span></li></ol>


四、Shell文件包含

像其他語言一樣,Shell 也可以包含外部腳本,將外部腳本的內容合並到當前腳本。
Shell 中包含腳本可以使用:
<ol class="snippet-num" ><li ><span class="sh_symbol" >.</span> filename</li></ol>


<ol class="snippet-num" ><li ><span class="sh_keyword" >source</span> filename</li></ol>

兩種方式的效果相同,簡單起見,一般使用點號(.),但是注意點號(.)和文件名中間有一空格。
例如,創建兩個腳本,一個是被調用腳本 subscript.sh,內容如下:
<ol class="snippet-num" ><li ><span class="sh_variable" >url</span><span class="sh_symbol" >=</span><span class="sh_string" >"http://see.xidian.edu.cn/cpp/view/2738.html"</span></li></ol>

一個是主文件 main.sh,內容如下:
[cpp] view
plain copy





#!/bin/bash
. ./subscript.sh
echo $url

執行腳本:
$chomd +x main.sh
./main.shhttp://see.xidian.edu.cn/cpp/view/2738.html $
注意:被包含腳本不需要有執行權限。
Copyright © Linux教程網 All Rights Reserved