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

相关文章
相关标签/搜索