+ -
当前位置:首页 → 问答吧 → shell函数能返回字符串吗?

shell函数能返回字符串吗?

时间:2011-07-22

来源:互联网

写了个函数
#!/bin/sh
function getTime
  {
    Time=`time`
    return $Time
  }
getTime
CurrentTime=$?
echo CurrentTime=$CurrentTime

想让他返回字符串Time,但是运行结果却是0,我怎么才能在shell函数中返回字符串呢?

>test1.sh
real    0m0.000s
user    0m0.000s
sys     0m0.000s
CurrentTime=0

作者: icetown   发布时间: 2011-07-22

回复 icetown


    shell 没有return 的`
用 echo
function getTime
  {
    Time=`time`
    echo  $Time
  }

作者: yangyang1581   发布时间: 2011-07-22

回复 icetown


    str=`getTime`

作者: yinyuemi   发布时间: 2011-07-22

time是直接输出到tty的,换个命令试试

#!/bin/sh
function getTime
  {
    date
  }

CurrentTime=$(getTime)
echo "CurrentTime=$CurrentTime"

作者: waker   发布时间: 2011-07-22

本帖最后由 icetown 于 2011-07-22 15:59 编辑

咋说呢,这个问题其实偶是比较关注shell是否返回值为字符串,而不是如何用`echo $Time`给变量赋值.
4楼的比较靠近真想了,把4楼的脚本稍微改了一下:

sh-3.2$ cat test2.sh
#!/bin/sh
function getTime
  {
    echo $1
    date
  }

CurrentTime=$(getTime "$1")
echo "CurrentTime=$CurrentTime"

结果:
sh-3.2$ test2.sh "abc"
CurrentTime=abc
Fri Jul 22 15:53:43 CST 2011

应该是把所有的函数里所有的输出都打印出来了,但实际上还不是返回值为字符串。

作者: icetown   发布时间: 2011-07-22