1. 程式人生 > >Linux Shell 之 Shell中的函式呼叫

Linux Shell 之 Shell中的函式呼叫

注意,()內是沒有引數的,它並不像C語言那樣,在()裡可以有引數。

二、函式的呼叫、使用
1、呼叫外部的函式,直接在本函式內新增
. fname.sh
然後:
fname  #不帶引數的
fname agr1 agr2   #帶引數的
2、本部的函式則可以直接使用
fname  #不帶引數的
fname agr1 agr2   #帶引數的

三、自定義函式
例如:判斷檔案是否存在
========
function fileExit()
{
    filename=$1 ;
    if [ -e "${filename}" ]
    then
        echo $1 " file is exit."
    else
        echo $1 " is not exit."
    fi
}
read -p "Please input the file name you want: " file ;
fileExit $file ;

========

例如:根據輸入的次數來進行列印
========
function LoopPrint()
{
    count=0;
    while [ $count -lt $1 ];
    do
    echo $count;
    echo $0;
    let ++count;
    sleep 1;
    done
    return 0;
}
read -p "Please input the times of print you want: " n ;
LoopPrint $n ;

==========

執行後輸入列印的次數,即可每個1s進行列印


關於函式中變數的含義如下:


$0:是指令碼本身的名字;
$#:是傳給指令碼的引數個數;
[email protected]:是傳給指令碼的所有引數的列表,即被擴充套件為"$1" "$2" "$3"等; $*:是以一個單字串顯示所有向指令碼傳遞的引數,與位置變數不同,引數可超過9個,即被擴充套件成"$1c$2c$3",其中c是IFS的第一個字元; $$:是指令碼執行的當前程序ID號;
$?:是顯示最後命令的退出狀態,0表示沒有錯誤,其他表示有錯誤;