help-bash
[Top][All Lists]
Advanced

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

Re: [Help-bash] Finding full path of sourced script


From: Suvayu Ali
Subject: Re: [Help-bash] Finding full path of sourced script
Date: Tue, 4 Sep 2012 15:21:48 +0200
User-agent: Mutt/1.5.21 (2011-07-01)

Hi Greg,

On Tue, Sep 04, 2012 at 08:23:09AM -0400, Greg Wooledge wrote:
> On Tue, Sep 04, 2012 at 01:15:00PM +0200, Suvayu Ali wrote:
> > I wanted to find the full path of a sourced script.  I cannot use
> > something like `basename $0` as $0 points to $BASH.
> 
> http://mywiki.wooledge.org/BashFAQ/028
> 

The article was very instructive.  Many of my doubts about using $0 were
confirmed.  :)

> > Is there a better alternative?
> 
> As I wrote on that wiki page, your best bet is either to hardcode the
> path of your data files inside the script, or to read a configuration
> file from a static location such as /etc/yourscript/config or
> $HOME/.yourscript.
> 
> Trying to determine "where the user put my script and its associated
> data files on the disk" is an impossible game.

In my use case, this is a setup script for a package which is always
within a directory by itself; the directory however can be in different
places on different systems, and the script can be sourced from any of
the directories in the package so hardcoding the path or requiring the
script to be in some standard directory is not an option.

To illustrate with an example:

  $ tree -d -L 1 $MYPACKAGEROOT 
  /workarea/SuperProject/MyPackage
  ├── include
  ├── data
  ├── dict
  ├── doc
  ├── plots
  ├── python
  ├── scripts
  ├── src
  ├── standalone
  ├── tests
  ├── tmp
  └── x86_64-slc5-gcc43-opt

The location of the setup script will always be
$MYPACKAGEROOT/standalone/setup.sh, but $MYPACKAGEROOT varies from
machine to machine.  The script needs to find out what the value of
$MYPACKAGEROOT should be, then set it and few other dependent variables.
I guess for this purpose $BASH_SOURCE seems to be the only way.  That
however means this won't work with zsh[1] or sh (using $0 works for zsh
though).

Thanks a lot for the help.

Cheers,


[1] sh, bash and zsh are the only supported shellsin our case.

-- 
Suvayu

Open source is the future. It sets us free.



reply via email to

[Prev in Thread] Current Thread [Next in Thread]