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