shell腳本處理大數據系列之(二)使用函數返回值

轉自http://longriver.me/?p=80shell

隨着shell腳本行數的增大,爲了編寫和維護的須要,想把一些特定的功能的代碼抽取出來,組成函數的形式,放到一個叫作functions.sh中這樣未來使用的時候只須要在腳本中source functions.sh 一下,而後就能夠方便使用,處理大數據的時候,上篇博文提到過使用多線程處理是重要的手段,因此想到了寫一個lock()函數,使得多個進程之間能夠異步的工做。bash

函數的返回值有兩種用途
1,返回函數結束的狀態(能夠是int,也能夠是string)
2,共享一些變量多線程

如下代碼來自異步

(EDIT: This is also true for some other shells...)
1. echo strings函數

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
lockdir= "somedir"
testlock(){
     retval= ""
     if mkdir "$lockdir"
     then # directory did not exist, but was created successfully
          echo >&2 "successfully acquired lock: $lockdir"
          retval= "true"
     else
          echo >&2 "cannot acquire lock, giving up on $lockdir"
          retval= "false"
     fi
     echo "$retval"
}
retval=$( testlock )
if [ "$retval" == "true" ]
then
      echo "directory not created"
else
      echo "directory already created"
fi

2. return exit status大數據

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
lockdir= "somedir"
testlock(){
     if mkdir "$lockdir"
     then # directory did not exist, but was created successfully
          echo >&2 "successfully acquired lock: $lockdir"
          retval=0
     else
          echo >&2 "cannot acquire lock, giving up on $lockdir"
          retval=1
     fi
     return "$retval"
}
 
testlock
retval=$?
if [ "$retval" == 0 ]
then
      echo "directory not created"
else
      echo "directory already created"
fi

3. share variableui

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
lockdir= "somedir"
retval=-1
testlock(){
     if mkdir "$lockdir"
     then # directory did not exist, but was created successfully
          echo >&2 "successfully acquired lock: $lockdir"
          retval=0
     else
          echo >&2 "cannot acquire lock, giving up on $lockdir"
          retval=1
     fi
}
 
testlock
if [ "$retval" == 0 ]
then
      echo "directory not created"
else
      echo "directory already created"
fi

【NOTICE】關於shell函數的一個陷阱,我曾經深嘗苦果,shell函數內部定義的變量,不是局部變量,這就意味着變量不會隨着函數的結束而消失,這個特色能夠被利用,因此shell函數中的變量要初始化,每次執行的時候注意從新賦值。spa

相關文章
相關標籤/搜索