[Novalug] How can script know if it's been 'sourced' rather than 'called'?

Richard Rognlie rrognlie at gamerz.net
Fri Apr 6 14:52:38 EDT 2007


On Fri, Apr 06, 2007 at 02:42:59PM -0400, Ben Creitz wrote:
> I have little script which starts ssh-agent for a given period of time
> and loads a private key.  The script must be "sourced" with source or
> . in order to work, so that the calling shell can access the env vars
> that ssh-agent exports.
> 
> Is there a way for the script to fail and echo proper usage if
> somebody calls it directly?  Of course, I can remove the execute bit.
> But I would like to avoid people calling it with
> 
>  bash start-ssh-agent 5
> 
> , too.  It really isn't too important, but I am curious to see if
> there's an answer out there.

You can use the $0 variable


test.sh
-------
#!/bin/bash

echo SHELL=$SHELL
echo 0=$0


if [ `basename $0` = bash ]; then
	echo sourced
else
	echo called
	exit 0;
fi




$ ./test.sh
SHELL=/bin/bash
0=./test.sh
called

$ . ./test.sh
SHELL=/bin/bash
0=/bin/bash
sourced

$ bash test.sh
SHELL=/bin/bash
0=test.sh
called




-- 
 /  \__  | Richard Rognlie / Sendmail Ninja / Gamerz.NET Lackey
 \__/  \ | http://www.gamerz.net/~rrognlie    <rrognlie at gamerz.net>
 /  \__/ | Creator of pbmserv at gamerz.net
 \__/    |                Helping reduce world productivity since 1994


More information about the Novalug mailing list