shell脚本处理大数据系列之(二)使用函数返回值

转自http://longriver.me/?p=80

随着shell脚本行数的增大,为了编写和维护的需要,想把一些特定的功能的代码抽取出来,组成函数的形式,放到一个叫做functions.sh中这样将来使用的时候只需要在脚本中source functions.sh 一下,然后就可以方便使用,处理大数据的时候,上篇博文提到过使用多线程处理是重要的手段,所以想到了写一个lock()函数,使得多个进程之间可以异步的工作。

函数的返回值有两种用途
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 variable

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函数中的变量要初始化,每次执行的时候注意重新赋值。

posted on 2014-03-14 14:05  Harveyaot  阅读(438)  评论(0编辑  收藏  举报

导航