7

I tried to use python practice if __name__ == "__main__": on shellscript.

Sample scripts are the following:

a.sh:

#!/bin/bash

filename="a.sh"

function main() {
  echo "start from $0"
  echo "a.sh is called"
  source b.sh
  bfunc
}

[[ "$0" == "${filename}" ]] && main

b.sh:

#!/bin/bash

filename="b.sh"

function main() {
  echo "start from $0"
  echo "b.sh is called"
}

function bfunc() {
  echo "hello bfunc"
}

[[ "$0" == "${filename}" ]] && main

You can call it with bash a.sh.

If you call bash a.sh, you'll get like the following:

start from a.sh
a.sh is called
hello bfunc

Here is my question. How can I get file name itself without using $0? I don't want to write file name directly, i.e. I want to pass the file name value to ${filename}.

See the link if you don't know that is the above python practice: What does if __name__ == "__main__": do?

How can I check wheather b.sh is started from command line or was executed by including from a.sh?

tkhm
  • 860
  • 2
  • 10
  • 30
  • 4
    side-note: The `function` keyword is superfluous in bash scripts plus it makes your script incompatible with POSIX for no reason. I'd remove it. – hek2mgl Jan 30 '18 at 07:57
  • 3
    i think, `$0` is the easiest way. Why you don't like it? – Viktor Khilin Jan 30 '18 at 07:58
  • 2
    @ViktorKhilin: `$0` refers to the executing program, but he wants to refer to the current file. If the current file is included from another script `$0` will give the wrong result. – clemens Jan 30 '18 at 08:05
  • @ViktorKhilin, easiest, but unreliable. See [BashFAQ #28](https://mywiki.wooledge.org/BashFAQ/028). – Charles Duffy Jan 31 '18 at 15:08

1 Answers1

7

You may use the variable $BASH_SOURCE to get the name of the current script file.

if [[ "$0" == "$BASH_SOURCE" ]]
then
    : "Execute only if started from current script"
else
    : "Execute when included in another script"
fi
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
clemens
  • 16,716
  • 11
  • 50
  • 65
  • You're missing some syntax here; as given, this will try to *run* `$0` (potentially recursing!) with the first argument `==`. Needs to be `[[ "$0" == "$BASH_SOURCE" ]]` or `[ "$0" = "$BASH_SOURCE" ]`. – Charles Duffy Jan 31 '18 at 15:09
  • Note only the single `=` in the `[` case -- that's because the [POSIX `test` specification](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/test.html) only specifies `=` as a string comparison operator; `==` is a nonportable extension... though if you're using `[[`, your code is nonportable anyhow, so it's less of a concern. – Charles Duffy Jan 31 '18 at 16:04
  • 1
    (Also, an `if` or `else` block that contains only a comment isn't valid syntax; you need *some* command, even if it's `true` or its synonym `:`). – Charles Duffy Jan 31 '18 at 17:28
  • @CharlesDuffy: Thanks, You‘re right, too much Python in mind. I would write an else block only if needed. – clemens Jan 31 '18 at 17:42