brent timothy saner on 18 Apr 2019 15:59:17 -0700

[Date Prev] [Date Next] [Thread Prev] [Thread Next] [Date Index] [Thread Index]

Re: [PLUG] Determining when a shell script is sourced

On 4/18/19 5:27 PM, K.S. Bhaskar wrote:
> We have a shell script (starts with #!/binsh and is at
> that should preferably not be source'd. Is there a way to test within
> the script whether someone has source'd it and generate an error without
> terminating the shell session that source'd it? Thank you very much.
> Regards
> – Bhaskar
> is probably the best
answer on this; a lot of it depends on whether your /bin/sh is linked to
bash, or if you need it to be POSIX-capable (i.e. /bin/sh is actually
Bourne instead of Bourne Again, or it's ASh, or something).

a couple big problems are:

- the $BASH_SOURCE array is bash-only

- $BASH_SOURCE doesn't reliably detect if something is sourced or not,
just if it's an interactive command entered vs. from a file (invoked or

- $_ doesn't work very reliably; you have ONE shot to capture it in the
script before it goes wonky:

$ echo 'this is an interactive command'
this is an interactive command
$ echo $_
this is an interactive command
$ /tmp/
$ . /tmp/
$ . /tmp/

$ cat /tmp/

echo ${_}

I'd stick to the POSIX-compat snippet in the answer I linked on SO,
since that has the least chance of futzing up.

Attachment: signature.asc
Description: OpenPGP digital signature

Philadelphia Linux Users Group         --
Announcements -
General Discussion  --