Shell函数(使用return命令)
(2018-08-21 14:30:49)
如果在函数里有Shell内置命令return,则函数执行到return语句时结束,并且返回到Shell脚本中调用函数位置的下一个命令。如果return带有一个数值型参数,则这个参数就是函数的返回值,返回值的最大值是255;否则,函数的返回值是函数体内最后一个执行的命令的返回状态。
函数中使用return命令实例
[root@aa ~]# cat checkif.sh
#!/bin/bash -
checkcount0()
{
return
0
}
if ( checkcount0 );then
echo
"0"
else
echo
"1"
fi
checkcount1()
{
return
1
}
if ( checkcount1 );then
echo
"0"
else
echo
"1"
fi
[root@aa ~]# ./checkif.sh
0
1
实例2
检查某个进程号是否存在,如果存在则返回0;不存在则返回1。
在函数中不使用return语句的情况下,除非发生语法错误或者一个同名并且为只读的函数已经存在,函数默认的返回值是0。
[root@aa ~]# ./checkpid.sh
These PIDS are not running!
[root@aa ~]#
[root@aa ~]#
[root@aa ~]#
[root@aa ~]#
[root@aa ~]#
[root@aa ~]# cat checkpid.sh
#!/bin/bash -
#检查某个进程号是否运行
checkpid()
{
#定义本地变量i
local
i
#使用for循环遍历传递给此函数的所有参数
for i in
$*
do
#如果目录/proc/$i存在,则执行此函数返回0
#在一般的Linux系统中,如果进程正在运行,则在/proc目录下会存在一个以进程号命名的子目录
[ -d "/proc/$i" ] && return 0
done
#返回1
return
1
}
#调用函数checkpid
checkpid $1 $2 $3
#如果上述命令执行成功,即$?的值等于0,则执行if中的语句
if [ $? = 0 ]
then
echo "The
one of them is
running."
else
echo "These
PIDS are not running!"
fi
[root@aa ~]# ./checkpid.sh 1048 2124 3590
The one of them is running.
实例3
[root@aa ~]# cat checkpid_if.sh
#!/bin/bash -
#检查某个进程号是否运行
checkpid()
{
#定义本地变量i
local
i
#使用for循环遍历传递给此函数的所有参数
for i in
$*
do
#如果目录/proc/$i存在,则执行此函数返回0
#在一般的Linux系统中,如果进程正在运行,则在/proc目录下会存在一个以进程号命名的子目录
[ -d "/proc/$i" ] && return 0
done
#返回1
return
1
}
if ( checkpid $1 $2 $3 );then
echo "The
one of them is running."
else
echo "These
PIDS are not running!"
fi
[root@aa ~]# ./checkpid_if.sh 1048 2124 3590
The one of them is running.
函数中使用return命令实例
[root@aa ~]# cat checkif.sh
#!/bin/bash -
checkcount0()
{
}
if ( checkcount0 );then
else
fi
checkcount1()
{
}
if ( checkcount1 );then
else
fi
[root@aa ~]# ./checkif.sh
0
1
实例2
检查某个进程号是否存在,如果存在则返回0;不存在则返回1。
在函数中不使用return语句的情况下,除非发生语法错误或者一个同名并且为只读的函数已经存在,函数默认的返回值是0。
[root@aa ~]# ./checkpid.sh
These PIDS are not running!
[root@aa ~]#
[root@aa ~]#
[root@aa ~]#
[root@aa ~]#
[root@aa ~]#
[root@aa ~]# cat checkpid.sh
#!/bin/bash -
#检查某个进程号是否运行
checkpid()
{
}
#调用函数checkpid
checkpid $1 $2 $3
#如果上述命令执行成功,即$?的值等于0,则执行if中的语句
if [ $? = 0 ]
then
else
fi
[root@aa ~]# ./checkpid.sh 1048 2124 3590
The one of them is running.
实例3
[root@aa ~]# cat checkpid_if.sh
#!/bin/bash -
#检查某个进程号是否运行
checkpid()
{
}
if ( checkpid $1 $2 $3 );then
else
fi
[root@aa ~]# ./checkpid_if.sh 1048 2124 3590
The one of them is running.
前一篇:Shell函数(本地变量)