Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash unexpected value of $0 inside script

Tags:

variables

bash

I have two files vars.sh and main.sh with the contents:

$ cat vars.sh
#!/bin/bash
fname="$0"        # should $0 equal 'vars.sh'?

$ cat main.sh
#!/bin/bash
echo $0
. vars.sh
echo $fname

When I run main.sh I get:

$ ./main.sh
./main.sh
./main.sh

My question is why is $0 inside vars.sh returning main.sh? I read man bash section about $0 but that did not help much.

like image 999
builder-7000 Avatar asked Dec 28 '25 22:12

builder-7000


2 Answers

Sourcing another script involves executing the sourced commands in the current shell. In the current shell, $0 refers to main.sh. You can think of sourcing as similar to "inclusion" or "copy-paste".

However, there does exist a way to get the sourced file name in bash. You can use BASH_SOURCE variable.

If you change vars.sh to:

#!/bin/bash
fname=${BASH_SOURCE[0]}

Then you'll get the sourced file's name as expected.

like image 96
P.P Avatar answered Dec 31 '25 12:12

P.P


It is because . (source) includes commands from sourced file, in your case from vars.sh

https://ss64.com/bash/source.html

like image 29
Rob Avatar answered Dec 31 '25 13:12

Rob



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!