Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect when a file is being sourced from bash [duplicate]

Tags:

linux

bash

shell

How do you determine if a file is being sourced from bash?

This is very similar to this question, however, none of the presented solutions work. For example, given the sourced file setup.bash:

if [ "$_" == "$0" ]
then
    echo "Please source this script. Do not execute."
    exit 1
fi

If you were to source this with: /bin/bash -c ". ./setup.bash;" you'll see the message printed "Please source this script. Do not execute.".

Why is this?

I'm sourcing the file this way because my end goal is to execute a bash script that relies on this sourced file, meaning I eventually want to do:

`/bin/bash -c ". ./setup.bash; some_command_that_relies_on_setup_dot_bash;"`

If I run these in bash directly, like:

. ./setup.bash
some_command_that_relies_on_setup_dot_bash

the sourced file doesn't display the message. What am I doing wrong?

like image 550
Cerin Avatar asked Mar 10 '17 07:03

Cerin


1 Answers

Using $_ can be error prone as it represents arguments from last executed command only.

It is better to check BASH_SOURCE instead like this:

if [[ "$0" = "$BASH_SOURCE" ]]; then
    echo "Please source this script. Do not execute."
fi

BASH_SOURCE variable always represents name of the script being executed i.e. ./setup.sh irrespective of the fact whether you are sourcing it in or not.

On the other hand $0 can be name of script when you directly execute it or be equal to -bash when you source it in.

like image 66
anubhava Avatar answered Nov 01 '22 04:11

anubhava