undefined behaviour of return statement in /bin/sh and missing man entry
Ian Lepore
ian at freebsd.org
Mon Aug 19 17:30:35 UTC 2019
On Mon, 2019-08-19 at 22:39 +0530, Mihir Luthra wrote:
> Hi everyone,
>
> Recently I was writing script on my virtual machine where I needed to
> know
> If a /bin/sh script has been sourced. I found many ways on
> stackoverflow,
> most of which only seem to work for bash. Although after some
> research, I
> found a way that should have worked with /bin/sh. It was that if I
> executed
> return from a function or sourced script, it should work fine and in
> other
> cases it should have wrote to stderr.
>
> Although on executing return on command line I got logged out and on
> executing same on non-login shells it just exited.
> Also, there seem to be no entry for return statement on man page of
> sh. [1]
>
> I have posted a brief explanation for the same in my stackoverfow
> question.
> [2].
>
> [1]
>
https://www.freebsd.org/cgi/man.cgi?query=sh&manpath=Unix+Seventh+Edition
> [2]
>
https://stackoverflow.com/questions/57547626/detect-if-a-script-has-been-sourced-in-bin-sh
>
You looked in the wrong set of manpages, right one [1] says...
The syntax of the return command is
return [exitstatus]
It terminates the current executional scope, returning from the
closest nested function or sourced script; if no function or
sourced script is being executed, it exits the shell instance. The
return command is implemented as a special built-in command.
I think when I tried to solve this problem once, the only thing I came
up with is the fact that $0 doesn't change when you source-in a script.
So if a given script knows what its name should be, and the expansion
of ${0##*/} doesn't match that name, it can mean the script was sourced
in. Or it can mean the user renamed the file or executed it through a
link, so it's not foolproof.
[1] https://www.freebsd.org/cgi/man.cgi?query=sh
-- Ian
More information about the freebsd-hackers
mailing list