7

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?

1

3 Answers 3

32

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.

Sign up to request clarification or add additional context in comments.

1 Comment

This should be the accepted answer since it gives more detail and explains the different scenarios clearer.
2

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

$BASH_ARGV

1 Comment

Means this is not generic. When parsing $ARGV you'll have to know about that you have been called by an other script. Maybe I'm wrong. If I'm wrong you should enhance explanation of your answer, e.g. add an example
0

create .sh file lets say view.sh then put

#!/bin/bash
echo "The script is being executed..."
readlink -f ${BASH_SOURCE[0]}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.