函數的返回值又可以稱為函數的退出狀態,實際上可以理解為一種通信方式。Shell腳本中函數可以使用返回值的方式把調用的結果信息反饋給調用者。便于調用者可以根據反饋的結果做相應處理。
說明:函數的返回值主要使用 return 關鍵字來處理。這和很多編程語言是一致的。
示例:判斷文件是否存在
cat checkFileExist.sh
#!bin/bash
File=/etc/hgm/
function checkFileExist()
{
if [ -f $File ];then
return 0
else
return 1
}
echo "Call function checkFileExist"
checkFileExist
if [ $? -eq 0 ];then #獲取checkFileExist的返回值
echo "$File 存在"
else
echo "$File 不存在"
File
執行命令:bash checkFileExist.sh
輸出結果:
Call function checkFileExist
/etc/hgm/ 文件不存在
技巧:$? 可以獲取上一個命令的返回值