国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 系統(tǒng) > Linux > 正文

Linux Shell函數(shù)返回值

2019-10-26 18:49:26
字體:
來源:轉載
供稿:網(wǎng)友

Shell函數(shù)返回值,一般有3種方式:return,argv,echo

1) return 語句
shell函數(shù)的返回值,可以和其他語言的返回值一樣,通過return語句返回。
示例:

#!/bin/bash -function mytest(){  echo "arg1 = $1"  if [ $1 = "1" ] ;then    return 1  else    return 0  fi}echo echo "mytest 1"mytest 1echo $?     # print return resultecho echo "mytest 0"mytest 0echo $?     # print return resultecho echo "mytest 2"mytest 2echo $?     # print return resultechoecho "mytest 1 = "`mytest 1`if mytest 1 ; then  echo "mytest 1"fiechoecho "mytest 0 = "`mytest 0`if mytest 0 ; then  echo "mytest 0"fiechoecho "if fasle" # if 0 is errorif false; then  echo "mytest 0"fiechomytest 1res=`echo $?`  # get return resultif [ $res = "1" ]; then  echo "mytest 1"fiechomytest 0res=`echo $?`  # get return resultif [ $res = "0" ]; then  echo "mytest 0"fiecho echo "end"

結果:
mytest 1
arg1 = 1
1

mytest 0
arg1 = 0
0

mytest 2
arg1 = 2
0

mytest 1 = arg1 = 1
arg1 = 1

mytest 0 = arg1 = 0
arg1 = 0
mytest 0

if fasle

arg1 = 1
mytest 1

arg1 = 0
mytest 0

end

先定義了一個函數(shù)mytest,根據(jù)它輸入的參數(shù)是否為1來return 1或者return 0.
獲取函數(shù)的返回值通過調(diào)用函數(shù),或者最后執(zhí)行的值獲得。
另外,可以直接用函數(shù)的返回值用作if的判斷。
注意:return只能用來返回整數(shù)值,且和c的區(qū)別是返回為正確,其他的值為錯誤。

2) argv全局變量
這種就類似于C語言中的全局變量(或環(huán)境變量)。
示例:

#!/bin/bash -g_var=function mytest2(){  echo "mytest2"  echo "args $1"  g_var=$1  return 0}mytest2 1echo "return $?"echoecho "g_var=$g_var"

結果:
mytest2
args 1
return 0

g_var=1

函數(shù)mytest2通過修改全局變量的值,來返回結果。

注: 以上兩個方法失效的時候
以上介紹的這兩種方法在一般情況下都是好使的,但也有例外。
示例:

#!/bin/bash -function mytest3(){  grep "123" test.txt | awk -F: '{print $2}' | while read line ;do    echo "$line"    if [ $line = "yxb" ]; then      return 0  # return to pipe only    fi  done  echo "mytest3 here "  return 1      # return to main process}g_var=function mytest4(){  grep "123" test.txt | awk -F: '{print $2}' | while read line ;do    echo "$line"    if [ $line = "yxb" ]; then      g_var=0      echo "g_var=0"      return 0  # return to pipe only    fi  done  echo "mytest4 here "  return 1}mytest3echo $?echomytest4echo $?echoecho "g_var=$g_var"

其中,test.txt 文件中的內(nèi)容如下:
456:kkk
123:yxb
123:test
結果:

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 中西区| 敖汉旗| 资中县| 清原| 南京市| 惠来县| 白沙| 鄢陵县| 息烽县| 龙海市| 安塞县| 克什克腾旗| 通海县| 阜宁县| 马山县| 黄冈市| 隆德县| 泽普县| 会理县| 长垣县| 汕头市| 卫辉市| 张家港市| 淳安县| 乌兰县| 河源市| 平阳县| 莲花县| 雅江县| 张家港市| 沈丘县| 崇文区| 礼泉县| 三门峡市| 林州市| 东宁县| 卓尼县| 蒙山县| 保康县| 泽库县| 喀喇|