当前位置: > shell编程 >

shell 函数返回值接收问题

时间:2015-10-10 12:33来源:linux.it.net.cn 作者:IT
  • 先测试第一个方法:
  • 测试第二个调用方式

注意第一个方式不是单引号!!!

先测试第一个方法:

 
1
2
3
4
5
6
7
8
9
10
#!/bin/bash
function check_user(){
  
   if [ "$1"X = "kerry"X ];then
        echo "administrator in check_user function"
   fi
  }
read username
result=`check_user $username`
echo "the result is:"${result}

函数的输出通过标准输出,然后传递给调用函数。结果如下:

 
1
2
3
[nxuser@PSBJ-0-0-0 tmp]$ ./testfunction.sh 
kerry
the result is:administrator in check_user function

如果被调用函数有多个echo输出,返回值是什么呢?是多个集合吗,还是只是一个?

 
1
2
3
4
5
6
7
8
9
10
11
#!/bin/bash
function check_user(){
  
   if [ "$1"X = "kerry"X ];then
        echo "administrator in check_user function"
        echo "added some other value"
   fi
  }
read username
result=`check_user $username`
echo "the result is:"${result}

结果如下,是多个echo的集合:

 
1
2
3
[nxuser@PSBJ-0-0-0 tmp]$ ./testfunction.sh 
kerry
the result is:administrator in check_user function added some other value

测试第二个调用方式

 
1
2
3
4
5
6
7
8
9
10
11
#!/bin/bash
function check_user(){
     
   if [ "$1"X = "kerry"X ];then
        echo "administrator in check_user function"
        echo "added some other value"
   fi
  }
read username
check_user $username
echo "the result is:"$?

输出结果如下:

 
1
2
3
4
5
[nxuser@PSBJ-0-0-0 tmp]$ ./testfunction2.sh 
kerry
administrator in check_user function
added some other value
the result is:0

很明显输出函数执行的返回值,成功为0. 因为没有显示的returen值。现在显示增加return代码

 
1
2
3
4
5
6
7
8
9
10
11
12
#!/bin/bash
function check_user(){
  
   if [ "$1"X = "kerry"X ];then
        echo "administrator in check_user function"
        return 8
          
   fi
  }
read username
check_user $username
echo "the result is:"$?

结果如下:

 
1
2
3
kerry
administrator in check_user function
the result is:8

 

(责任编辑:IT)
------分隔线----------------------------
栏目列表
推荐内容