Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the script name being executed in bash?

So I am trying to make a portable bashrc/bash_profile file. I have a single script that I am symbolically linking to .bashrc, .bash_profile, etc. I am then looking at $0 and switching what I do based on which script was called. The problem is what the shell calls the bashrc script of course it executes bash really which means $0 for me is -bash. $1 further more is not set to the script name.

So my question is, in bash how can I get the name of the script being executed. Not the binary executing it, e.g. bash?

I assume its giving me -bash with $1 not being set because it is really not a new process. Any ideas?

like image 525
David Mokon Bond Avatar asked Feb 12 '13 14:02

David Mokon Bond


2 Answers

Try:

readlink -f ${BASH_SOURCE[0]}

or just:

${BASH_SOURCE[0]}.

Remarks:

$0 only works when user executes "./script.sh"

$BASH_ARGV only works when user executes ". script.sh" or "source script.sh"

${BASH_SOURCE[0]} works on both cases.

readlink -f is useful when symbolic link is used.

like image 125
Hui Zheng Avatar answered Nov 26 '22 01:11

Hui Zheng


The variable BASH_ARGV should work, it appears the script is being sourced

$BASH_ARGV
like image 24
Zombo Avatar answered Nov 26 '22 02:11

Zombo