3

I was reading about traps, but only return works for me in my shell script, so was wondering what status or code it returns, so what I tried is,

#!/bin/bash
seeOutput=`return`
echo $seeOutput

It's just returning a new line and when done on terminal, it says,

-bash: return: can only `return' from a function or sourced script

which I already know :p I just need to know "return"'s exit status.

6
  • return defaults to true. bash 4.3 has included return -1 which means error. Thus return accept negative values as return value (e.g. return -1 will show as (8 bit) 255 in the caller). See wiki.bash-hackers.org/scripting/bashchanges Commented Aug 6, 2014 at 12:35
  • There's a good answer on StackOverflow for this question. Commented Aug 6, 2014 at 12:39
  • 1
    @val0x00ff, no, return defaults to return "$?" (that is, it returns with the exit status of the last run command). Commented Aug 6, 2014 at 12:42
  • @StéphaneChazelas What I was meaning to say. Usually return on its own indicates true as you'd do in c return 0 to indicate success. Anything else will be false and ofcourse based on the status of $? returned from the last command. e.g f(){ args=2; [[ $# = $args ]] && return || return ; }; f 1 Will hit the second return which will be false. However f(){ args=2; [[ $# = $args ]] && return || return ; }; f 1 2 will hit the first return which will be true. Commented Aug 6, 2014 at 13:02
  • Since you know that you can only call return from a function or a sourced script, why are you calling it in another context? What do you expect to happen? And what do you mean by “ "return"'s exit status”? Since return causes its context to exit, there's no way to observe any exit status of the return instruction itself, what you observe is the exit status of the containing function or sourced script. Commented Aug 6, 2014 at 23:01

3 Answers 3

4

What you're doing is calling a shell command return which doesn't make sense. In general, return with no value followed returns the exit status of the last command executed.

From man: Causes a function to exit with the return value specified by n. If n is omitted, the return status is that of the last command executed in the function body.

1
  • But actually I was using return to just to get out of my script(If one of the command-line argument is missing) Thanks for adding this too to my knowledge! :) Commented Aug 6, 2014 at 12:48
3

return code is stored in $? variable.

false ; echo $?
true ; echo $?

would return

1
0

unix convention is that 0 means OK. in your exemple, seeOuput hold whatever output from the back quoted command.

Do not mistake output and return code.

-1

This is how I used it:

f()
{
   ls $AAA
   return $?
}

g()
{
   f
   return $?
}

d()
{
   g
   echo $?
}

AAA=
d

_

<contents of dir>
0

_

AAA=sdsasdasd
d

_

ls: sdsasdasd: No such file or directory
2

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .