Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get shellscript filename without $0?

Tags:

python

bash

shell

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?

like image 738
tkhm Avatar asked Jan 30 '18 07:01

tkhm


People also ask

How do I get filename in shell without extension?

Using Bash, there's also ${file%. *} to get the filename without the extension and ${file##*.} to get the extension alone. That is, file="thisfile.

What is $? == 0 in shell script?

$? is the exit status of the most recently-executed command; by convention, 0 means success and anything else indicates failure. That line is testing whether the grep command succeeded. The grep manpage states: The exit status is 0 if selected lines are found, and 1 if not found.

What is $0 used for in shell script?

($0) Expands to the name of the shell or shell script. This is set at shell initialization. If Bash is invoked with a file of commands (see Shell Scripts), $0 is set to the name of that file.


1 Answers

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
like image 180
clemens Avatar answered Oct 09 '22 16:10

clemens