Home > Back-end >  How to get sourcing script (BASH_ENV, $0)?
How to get sourcing script (BASH_ENV, $0)?

Time:08-20

Case

According to gnu.org, BASH_ENV behaves for non-interactive scripts as follows:

if [ -n "$BASH_ENV" ]; then . "$BASH_ENV"; fi

A sourced script might get its sourcing part via $0 (I know it is bit of a hack).

foo:

echo foo
. bar.sh

bar.sh:

#!/bin/bash
echo bar
echo \$0: $0
user@myhost:~/test$ ./foo
foo
bar
$0: ./foo

But when using BASH_ENV , $0 inside the referenced script will have the name of the executed command, not of sourcing script ./foo

.bashenv:

echo "Started script $0"
user@myhost:~/test2$ BASH_ENV=.bashenv ./foo
Started script /bin/bash

Question

For debugigng purposes I'd like to log output "Started script xy" for each script invoked as part of one main root script.

Goal is to not log the name manually in each script (DRY). BASH_ENV might be the solution here. But how do I get the name of the sourcing script inside the script? Or is there a better solution?

CodePudding user response:

Can you try ?

echo "Started script $_"
  • Related