开发者

Unix shell functions, command substitution and exit

Please explain me about how to use unix shell function correctly.

For example we have following functions f and g:

f()
{
   #do something
   return $code
}

g()
{
   print $something
}

We can use function f in the next way:

f
if [[ $? -eq 0 ]]; then
   #do 1
else
   #do 2
fi

This function performs some work and exits with some exit status.

And we can analyze this exit status.

We can use function g in the next way:

g

or

result=$(g)
if [[ $result = "something" ]]; then
   #do something
fi

In first case we just called function.

In the second case we used command substitution to assign all text that function prints to stdout to variable result.

But what if there is following function:

z()
{
   user=$1
   type=$2
   if [[ $type = "customer" ]]; then
      result=$(/somedir/someapp -u $user)
      if [[ $result = "" ]]; then
         #something goes wrong
         #I do not want to continue
   开发者_开发百科      #I want to stop whole script
         exit 1
      else
         print $result
      fi
   else
      print "worker"
   fi
}

I can use function z in the next way:

z

If something goes wrong then whole script will be stopped.

But what if somebody uses this function in command substitution:

result=$(z)

In this case if someapp returns empty string script will not be stopped.

Is it not correct approach to use exit in functions?


I don't have a way to test this right now, but ksh (maybe bash too), can scope variables inside functions.

z()
{
   typeset result
   user=$1
   type=$2
   if [[ $type = "customer" ]]; then
      result=$(/somedir/someapp -u $user)
      if [[ $result = "" ]]; then
         #something goes wrong
         #I do not want to continue
         #I want to stop whole script
         exit 1
      else
         print $result
      fi
   else
      print "worker"
   fi
}

Notice the insertion of typeset result near the top.

You may need to use the alternate declartion of function for this feature to work, i.e.

 function z {
    #....
  }

I hope this helps.

You could also do something like

  result=$(z ; "eval retCode=\$? ; echo \$retCode" )
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜