#!/bin/bash
function test()
{
echo $#
for param in $*
do
echo "param " $param
done
return 9;
}
echo "before call test"
test "ab" "cd" "ef"
result=$? # 這裏的返回值不能超過 255
echo "after call test"
echo $result
========================================
$0:是腳本本身的名字;
$#:是傳給腳本的參數個數;
$@:是傳給腳本的所有參數的列表,即被擴展爲"$1" "$2" "$3"等;
$*:是以一個單字符串顯示所有向腳本傳遞的參數,與位置變量不同,參數可超過9個,即被擴展成"$1c$2c$3",其中c是IFS的第一個字符;
$$:是腳本運行的當前進程ID號;
$?:是顯示最後命令的退出狀態,0表示沒有錯誤,其他表示有錯誤;
========================================
如果函數想返回字符串
function fun()
{
echo "abc"
}
result=$(fun) # 這裏講返回的字符串保存到變量裏
========================================
#!/bin/bash
function little_addfunc()
{
# 這裏不能讓兩個數的和大於255,要不 $? 該反轉保存了
echo "addfunc in"
echo $1
echo $2
return $(($1+$2))
}
function stringCombin()
{
echo "$1$2"
}
function big_addfunc()
{
#這裏沒有什麼關係,按照正常的加法進行,沒有使用return語句
echo `expr $1 + $2`
}
echo "test begin"
echo "== little_addfunc =="
little_addfunc 100 155 # 預期傳入的數字是 100 和 155
total=$?
echo "total = $total"
echo "== stringCombin =="
result=$(stringCombin "ab" "cd")
echo "result = $result"
echo "== big_addfunc =="
res=$(big_addfunc 100 200) # 將結果保存成了數字
echo "res = $res"
echo `expr $res + 100`