函數(shù)
定義:
1、無返回值
#function為關(guān)鍵字,F(xiàn)UNCTION_NAME為函數(shù)名
function FUNCTION_NAME(){
command1
command2
...
}
省略關(guān)鍵字function,效果1樣
FUNCTION_NAME(){
command
....
}
例:
1、簡單函數(shù)聲明和調(diào)用
#!/bin/bash
function sayHello(){
echo "Hello World!"
}
sayHello
注意:
1、sayHello調(diào)用的時候沒有(),sayHello()這樣的調(diào)用會出錯。
2、如果先調(diào)用再聲明,則調(diào)用和聲明之間不能有其他語句
2、計算文件的行數(shù)
#!/bin/bash
if [[ $# -lt 1 ]];then
echo "Please input a filename."
return
fi
file=$1
countLine
function countLine(){
local line=0
while read
do
let "line++";
done < $file
echo "$file has $line lines."
}
2、函數(shù)的返回值
return
獲得返回值的主要方式是$?
例:
#檢測文件是不是存在
#!/bin/bash
file=$1
check
if [ $? -eq 0 ];then
echo "$file exists."
else
echo "$file doesn't exist."
fi
function check(){
if [ -e $file ];then
return 0
else
return 1
fi
}
3、帶參數(shù)的函數(shù)
1、位置參數(shù)
這個和高級語言不1樣,在函數(shù)聲明里沒有指定參數(shù),而是直接在函數(shù)體里使用,調(diào)用的時候直接傳入?yún)?shù)便可
例:
1、檢測文件是不是存在
#!/bin/bash
check $1 #這里不再使用file變量
if [ $? -eq 0 ];then
echo "$1 exists."
else
echo "$1 doesn't exist."
fi
function check(){
if [ -e $1 ];then #函數(shù)體里的參數(shù)
return 0
else
return 1
fi
}
2、計算兩數(shù)之和
#!/bin/bash
function add(){
local tmp=0
i=$1
j=$2
let "tmp=i+j"
return $tmp
}
add $1 $2
echo "$?"
2、指定位置參數(shù)值
使用set內(nèi)置命令給腳本指定位置參數(shù)的值(又叫重置)。1旦使用set設(shè)置了傳入?yún)?shù)的值,腳本將疏忽運行時傳入的位置參數(shù)(實際上是被set
重置了位置參數(shù)的值)
例:
#!/bin/bash
set 1 2 3 4
count=1
for var in $@
do
echo "Here $$count is $var"
let "count++"
done
注意:輸入時不管有多少參數(shù)都重置為4個參數(shù)。
如:
. ./function03.sh a b c d e f
結(jié)果:
Here $1 is 1
Here $2 is 2
Here $3 is 3
Here $4 is 4
注意:有甚么意義?
3、移動位置參數(shù)
回顧:
shift,在不加任何參數(shù)的情況下,這個命令可以將位置參數(shù)向左移動1位。
例:
#!/bin/bash
until [ $# -eq 0 ]
do
echo "Now $1 is:$1,total paramert is:$#"
shift
done
注意:活用位置參數(shù),
$@/$*:所有參數(shù)
$1..$n:第n個參數(shù),當n大于10時,要將n用()括起來
$0:腳本本身
當用‘.’履行腳本時為bash
當用bash履行腳本時返回的文件名
當用./scriptname履行時返回./scriptname
$#:所有參數(shù)
擴大
指定左移的位數(shù),shift n
例:
#!/bin/bash
echo "$0"
until [ $# -eq 0 ]
do
echo "Now $1 is:$1,total paramert is:$#"
shift 2
done
注意:如果輸入命令時指定了奇數(shù)個參數(shù),則腳本會墮入死循環(huán)。
4、函數(shù)庫
為了和普通函數(shù)區(qū)分,在實踐中,建議庫函數(shù)使用下劃線(_)開頭
加載庫函數(shù):
1、使用"點"(.)命令
2、使用source命令
例:
1、建立函數(shù)庫
實際上就是寫1個都是函數(shù)的腳本文件
例:建立庫lib01.sh
function _checkFileExist(){
if [ -e $1 ];then
echo "File:$1 exists"
else
echo "File:$1 doesn't exists"
fi
}
2、使用
#!/bin/bash
#source ./lib01.sh
. ./lib01.sh
_checkFileExist $1
系統(tǒng)函數(shù)庫:
/etc/init.d/functions(我的系統(tǒng)是ubuntu,沒看到這個文件)
1個27個函數(shù)
上一篇 mysql字符串類型
下一篇 算法時間復(fù)雜度計算