-   Linux - Software (
-   -   how can a shell script determine its own location when being sourced? (

DeuceNegative 02-12-2008 10:09 PM

how can a shell script determine its own location when being sourced?
I have a script that needs to be sourced, not executed. What can I use inside this script to determine the full path to itself, so I can compute some variables relative to it?

If it was always sourced in the same directory as it resides (not an option) I would of course use "$PWD". If it was being executed, I would use "$0". If it was a python script, I could also use __file__. Etc. But I can't think of a solution for the basic situation here.

Thanks in advance for any help.

maroonbaboon 02-13-2008 10:18 PM

How about putting

cmdline=`history 1`

at the start of the script? Then $cmdline gives the commandline for the source command.

DeuceNegative 02-15-2008 05:12 PM

Thanks for the help. I never thought of that, and I'm definitely going to use it in some of my scripts.

However, I hesitate to rely on it in production releases. That variable will be the whole command line, including any other commands composed with it using `;', and the very problem I'm having is causing people to do that very often (cd $location; source ./; cd $OLDPWD).

Splitting on `;' would be easy enough, but there are lots of other shell metacharacters that could come into play. Though unlikely, the command could be used in conjunction with commands like time and watch, and environment variables are still sitting there unevaluated.

For example,


time { source "$user_defined_variable"/; myprogram; }
Even if I could write the code to determine that path to in this case, I would not trust it in general.

maroonbaboon 02-15-2008 11:59 PM

Yes, I thought it was a bit kludgy, but it seemed like the file had already been closed by the time the commands started to execute, so in that sense the location of the file really was just 'history'.

I had another look at the man page for bash. Have you looked at the BASH_SOURCE variable? It seems to be giving what you want inside the script.

archtoad6 02-19-2008 01:51 PM

${BASH_SOURCE} should be just what you're asking for.

${BASH_SOURCE%/*} should give you the path you need.

${BASH_SOURCE##*/} would give just the actual name of the file, just in case you need to know the name it was called by.

BTW, what did you do/use?

In the bash man page, which is long & sometimes confusing, search for:
  • ${parameter#word}

DeuceNegative 02-21-2008 02:57 PM

Thanks a lot! BASH_SOURCE is exactly what I was looking for.

Unfortunately it seems to not be available before bash version 3, and I would like a solution for csh, too, but I can deal with those situations as special cases.

For the vast majority of users, problem solved.

All times are GMT -5. The time now is 07:37 AM.