JP Vossen on 18 Apr 2019 15:11:27 -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.

It looks like TB is screwing up the line breaks as usual, but this is what I wrote when I had to do something like the opposite. Basically, I have a config file I source that in some special cases I need to execute so it can test things it contains. I suspect you can easily hack that into what you need, but I haven't looked at your code.

----
# Only execute this block if we are being executed, NOT sourced!!!
# Sourced: "${BASH_SOURCE[0]}" is this script and "${0}" is calling script (or "bash" if CLI) # Executing: "${BASH_SOURCE[0]}" is this script and "${0}" (caller) is this script!
    # BUT, when sourced recursively the caller *is* this
    # script, which looks like executing, but the stack is pushed so:
    # "${BASH_SOURCE[1]}" == "${BASH_SOURCE[0]}" == "${0}" = this script
    # So we only want to execute when we do NOT have "${BASH_SOURCE[1]}":
[ "${BASH_SOURCE[0]}" == "${0}" -a -z "${BASH_SOURCE[1]}" ] && {
    : stuff here
}
----

Anyone have any better ideas?

HTH,
JP
--  -------------------------------------------------------------------
JP Vossen, CISSP | http://www.jpsdomain.org/ | http://bashcookbook.com/
___________________________________________________________________________
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