K.S. Bhaskar on 6 May 2019 10:06:41 -0700


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

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


Here's the basic structure that I used (I want the script to work whether or not it has a .sh extension; depending on the context, it could be one way or the other):

$ cat bin/shelltest.sh
#!/bin/sh -
cmd=`basename $0`
base=`basename -s .sh $0`
dir=`dirname $0`
if [ "shelltest" = $base ] ; then
    if [ $PWD = $dir -o "." = $dir ] ; then
    echo Put code here to run
    else
    echo "Please cd to $dir and then execute $cmd"
    fi
else
    echo "Please execute the file instead of sourcing it"
    return
fi
$ bin/shelltest.sh
Please cd to bin and then execute shelltest.sh
$ source bin/shelltest.sh
Please execute the file instead of sourcing it
$ ( cd bin ; ./shelltest.sh )
Put code here to run
$

Thanks all for the suggestions.

Regards
– Bhaskar

On Fri, Apr 19, 2019 at 10:50 AM K.S. Bhaskar <ksbhaskar@gmail.com> wrote:
Thanks for the ideas. I'll see what I can make work and get back with what I come up with. The problem is not about leaking into the shell, it is about protecting against user error – the script unfortunately closes the shell session if sourced, which it does not do if run as a script.

Regards
– Bhaskar

On Thu, Apr 18, 2019 at 10:33 PM <gary@duzan.org> wrote:
   If this is a concern, a better approach may be to have the script clean
up after itself so that nothing leaks into the shell that sources it.
In bash, at least, you can do things like "unset -f" to get rid of
functions, "type -t" to check for existing functions so you don't
replace them, etc.

                             Gary Duzan



___________________________________________________________________________
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
___________________________________________________________________________
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