Skip site navigation (1)Skip section navigation (2)
Date:      Mon, 19 Aug 2019 11:30:30 -0600
From:      Ian Lepore <ian@freebsd.org>
To:        Mihir Luthra <luthramihir708@gmail.com>, freebsd-hackers@freebsd.org
Subject:   Re: undefined behaviour of return statement in /bin/sh and missing man entry
Message-ID:  <b6f4236defc3f46ca3542b2ed81f9a5e7c7b4407.camel@freebsd.org>
In-Reply-To: <CAEa=dYBsOcmrkf=sOFwPY0-TJDbY_ooMzqDDth4SBAGV0BXpUQ@mail.gmail.com>
References:  <CAEa=dYBsOcmrkf=sOFwPY0-TJDbY_ooMzqDDth4SBAGV0BXpUQ@mail.gmail.com>

next in thread | previous in thread | raw e-mail | index | archive | help
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




Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?b6f4236defc3f46ca3542b2ed81f9a5e7c7b4407.camel>