Determine the name of a calling Bash script .

I have a Bash setup script which is called by many other scripts.  For example I have a script named myScript1 that looks like:

#!/bin/bash
. ./setup.sh

How can setup.sh determine the name of the script that called it?
Thanks - Terry
TerryNJonesAsked:
Who is Participating?
 
woolmilkporcConnect With a Mentor Commented:
The whole path is in $0.

Find the filename alone with

scriptname=$(basename $0)echo $scriptname

0
 
ozoCommented:
If you invoke it with .
you can find the name of the caller in $0

0
 
hemmiCommented:
That's total nonsense: $0 will of course only show setup.sh itself and not the calling script!
The viriable PPID will hold the parents process id.
Under
/proc/$PPID
you will find everything you want to know about the calling process!
0
The 14th Annual Expert Award Winners

The results are in! Meet the top members of our 2017 Expert Awards. Congratulations to all who qualified!

 
woolmilkporcCommented:
OK,
 
 it seems that you want to find out the name of the calling ("parent") script!
 
 There is a variable containing the PID of the parent, which you could evaluate in the following way:

parent=$(ps -f -p $PPID | tail -1 | awk '{print $NF}')

0
 
woolmilkporcCommented:
... and again for the scriptname alone:

 parentfile=$(basename $(ps -f -p $PPID | tail -1 | awk '{print $NF}'))
0
 
TerryNJonesAuthor Commented:
Exactly what I needed!  Thanks.
0
 
hemmiCommented:
It's not that easy, woolmilkporc ... That why I proposed to use all information on the calling process.
If the calling process had been call with some parameters, say
myscript -p1 -p2
then look what your "solution" does ...

0
 
ollfriedCommented:
@hemmi: $0 (better: ${0}) together with basename was the correct answer. Please do not other people the way you do and call solutions nonsense.
0
 
hemmiCommented:
I'm sorry. I did not see the leading "." in the original post. So it seems guaranteed, that he's always sourcing the script and not calling the script!
Still - in case of actually calling - your basename will not work in all cases.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.