source filename
or
. filename
底下是一個會將參數累加起來的 function
範例:
共用 script (func.sh)
#!/bin/sh
sum()
{
total=0
count=0
echo The PID of sum\(\) = $$
if [ "$#" -lt "2" ]; then
echo "The number of arguments should larger than 1."
return 255;
fi
for i in $@
do
((total += i))
((count += 1))
echo -n $i
if [ "$count" -lt "$#" ]; then
echo -n " + "
fi
done
echo " = $total"
return $total
}
測試 script (test.sh)
#!/bin/sh
source ./func.sh
echo The PID of $0 = $$
echo ""
sum 1 2
echo The return of sum\(\) = $?
echo ""
sum 3 4 5
echo The return of sum\(\) = $?
echo ""
sum 6
echo The return of sum\(\) = $?
結果:
The PID of ./test.sh = 2075
The PID of sum() = 2075
1 + 2 = 3
The return of sum() = 3
The PID of sum() = 2075
3 + 4 + 5 = 12
The return of sum() = 12
The PID of sum() = 2075
The number of arguments should larger than 1.
The return of sum() = 255
說明:
test.sh 在開頭使用 source 引入 func.sh 後呼叫了三次 sum(),從 PID 可以看出,sum() 是由執行 test.sh 的 process 所執行。
沒有留言:
張貼留言