Search code examples
bashcygwin

Cygwin $0 not working as exptected


I have an odd behavior of $0 under cygwin.

In my script, I do echo "$0", and get as output -bash instead of the pathname. However, if I do realpath $0, i get the actual path. Why is that, and do other people encounter this, too?

I am trying to source the script, does this change things?


Solution

  • Yes, sourcing is the reason. Sourcing does not start a different process, so things like $0 will continue to have their values when the script is being sourced.

    Here is a script myname:

    #!/bin/bash
    echo "$0"
    

    Here is the sourcing:

    $ source myname
    -bash
    

    And here is running the script:

    $ ./myname
    ./myname
    

    There you are!

    Update: This is not cygwin specific. All shells should behave this way, by design.