Returning value from called function in a shell script

后端 未结 5 522
自闭症患者
自闭症患者 2020-11-27 08:55

I want to return the value from a function called in a shell script. Perhaps I am missing the syntax. I tried using the global variables. But that is also not working. The c

5条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-27 09:33

    I think returning 0 for succ/1 for fail (glenn jackman) and olibre's clear and explanatory answer says it all; just to mention a kind of "combo" approach for cases where results are not binary and you'd prefer to set a variable rather than "echoing out" a result (for instance if your function is ALSO suppose to echo something, this approach will not work). What then? (below is Bourne Shell)

    # Syntax _w (wrapReturn)
    # arg1 : method to wrap
    # arg2 : variable to set
    _w(){
    eval $1
    read $2 <

    as in (yep, the example is somewhat silly, it's just an.. example)

    getDay(){
      d=`date '+%d'`
      [ $d -gt 255 ] && echo "Oh no a return value is 0-255!" && BAIL=0 # this will of course never happen, it's just to clarify the nature of returns
      return $d
    }
    
    dayzToSalary(){
      daysLeft=0
      if [ $1 -lt 26 ]; then 
          daysLeft=`expr 25 - $1`
      else
         lastDayInMonth=`date -d "`date +%Y%m01` +1 month -1 day" +%d`
         rest=`expr $lastDayInMonth - 25`
         daysLeft=`expr 25 + $rest`
      fi
      echo "Mate, it's another $daysLeft days.."
    }
    
    # main
    _w getDay DAY # call getDay, save the result in the DAY variable
    dayzToSalary $DAY
    

提交回复
热议问题