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
> https://gitlab.com/YottaDB/DB/YDB/blob/master/sr_unix/ydbinstall.sh)
> 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
> 


https://stackoverflow.com/a/28776166/11365825 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
sourced)

- $_ 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/test.sh
/tmp/test.sh
$ . /tmp/test.sh
_filedir
$ . /tmp/test.sh
/tmp/test.sh

$ cat /tmp/test.sh
#!/bin/bash

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         --        http://www.phillylinux.org
Announcements - http://lists.phillylinux.org/mailman/listinfo/plug-announce
General Discussion  --   http://lists.phillylinux.org/mailman/listinfo/plug