Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if a shell script file is sourced in Bash [duplicate]

Tags:

bash

shell

I want to how to determine if a script file is executed or sourced.

For example,

# Shell script filename build.sh
if [ "x$0" = "xbash" ]; then
    echo "I am sourced by Bash"
else
    echo "I am executed by Bash"
fi

If I typed

source build.sh

it would output I am sourced by Bash.

If I typed

./build.sh

it would output I am executed by Bash.

Currently, I use $0 to do this. Is there a better idea?

Inspired by Tripeee, I found a better way:

#!/bin/bash

if [ "x$(awk -F/ '{print $NF}' <<< $0)" = 'xcdruntime' ]; then
    echo Try to source me, not execute me.
else
    cd /opt/www/app/pepsi/protected/runtime
fi
like image 255
hellojinjie Avatar asked Mar 24 '12 08:03

hellojinjie


1 Answers

It doesn't work if sourced by another script. I would go the other way around;

test "X$(basename -- "$0")" = "Xbuild.sh" || echo Being sourced

Update: added X prefix to both strings.

Update too: added double dash to basename invocation.

like image 165
tripleee Avatar answered Sep 18 '22 15:09

tripleee