天天看點

linux shell傳回值方式及示例概述

版權聲明:本文為部落客轉載文章,碼字不易,轉載請标明出處。 https://blog.csdn.net/yue530tomtom/article/details/76094008

概述

  Shell函數傳回值,常用的兩種方式:echo和return

echo

據man手冊描述:echo是一個輸出參數,有空格分割,會産生一個新行。傳回永遠是0。

echo一般起到一個提示的作用。在shell程式設計中極為常用, 在終端下列印變量value的時候也是常常用到的。

在shell中子程序會繼承父程序的标準輸出,是以,子程序的輸出也就直接反應到父程序。是以函數的傳回值通過輸出到标準輸出是一個非常安全的傳回方式。

使用echo傳回的示例

[[email protected] ~]# cat echoTestFun.sh 
#!/bin/bash  
function echoTestFun()  
{  
    if [ -z $1 ] 
    then  
        echo "0"  
    else  
        echo "$@"  
    fi  
}
echo "Agrs not null start:"
echoTestFun $@  
echo "Agrs not null end"
echo "Agrs  null start:"
echoTestFun  
echo "Agrs  null end"
           

執行

[[email protected] ~]# ./echoTestFun.sh 1 hh 3
Agrs not null start:
1 hh 3
Agrs not null end
Agrs  null start:
0
Agrs  null end
           

return

shell函數的傳回值,可以和其他語言的傳回值一樣,通過return語句傳回,BUT return隻能用來傳回整數值;且和c的差別是傳回為正确,其他的值為錯誤。

使用return傳回的示例

[[email protected] ~]# cat returnTestFun.sh 
#!/bin/bash  
function returnTestFun()  
{  
    if [ -z $1 ]
    then  
        return 0  
    else  
        return 1  
    fi  
}
echo "Agrs not null start:"
returnTestFun $@  
echo $?
echo "Agrs not null end"
echo "Agrs  null start:"
returnTestFun
echo $?
echo "Agrs  null end"
           

執行

[[email protected] ~]# ./returnTestFun.sh hello world
Agrs not null start:
1
Agrs not null end
Agrs  null start:
0
Agrs  null end
           

若傳回不是整數的傳回值,将會得到一個錯誤 

如把上例中的return 1改為return $1,使用同樣的參數運作将得到提示:

./returnTestFun.sh: line 8: return: hello: numeric argument required
           

版權聲明:本文為部落客轉載文章,碼字不易,轉載請标明出處。 https://blog.csdn.net/yue530tomtom/article/details/76094008

繼續閱讀