0

Having a simple script:

echo "file: $0"

when invoked like so:

bash myscript.sh

or

./myscript.sh

gives file name of the script (file: myscript.sh) as expected but when invoked:

source myscript.sh

or

. ./myscript.sh

gives the shell name (bash) instead of script file name.

Why is it like this?

2

The first call will start a new instance of bash to interpret the script, meaning bash will set $0 to its path.

The second call will treat the file as executable and run it, so $0 will point to it.

The latter two calls will load the file into the current instance of bash, so $0 will point there.

NB: #2 needs the file to be executable, #1, #3 and #4 not.

  • 1
    #1 doesn't need the file to be executable, only #2 does – Eric Renouf May 24 '17 at 12:05
  • Reading more carefully would have helped - thanks for the catch! – Eugen Rieck May 24 '17 at 22:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.