5

In school I learned that "$0" would be the name of the script in bash, but when I try to print it, it actually prints -bash instead of the scriptname.

#!/bin/bash
echo "$0"

Output: -bash

Is there something I missed, or is there another command to get the name of the script?

Stefan
  • 1,122
  • 3
  • 14
  • 38
  • 1
    Use `$BASH_SOURCE`, not `$0`. `$0` is generally unreliable, as described in [BashFAQ #28](https://mywiki.wooledge.org/BashFAQ/028). – Charles Duffy Apr 16 '18 at 15:04

2 Answers2

4

Use $BASH_SOURCE, not $0, as described in BashFAQ #28 -- or, even better, don't rely on being able to accurately determine your script's location at all.

  • $0 is set by the caller, and can be any arbitrary string -- it's not guaranteed to have anything to do with the location from which the script is read.

    To demonstrate this, try running (exec -a arbitrary-name ./your-script), which will execute your-script with $0 set to arbitrary-name.

  • $0 is not updated appropriately when a script is sourced, or when a function read from a file is executed from somewhere else; whereas $BASH_SOURCE is updated in these cases.

  • A local filename may not exist at all: Consider the case where your script is run with ssh remotehost 'bash -s' <./scriptname: There is no local filename that corresponds with your script's source.

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
2

You are running the echo "$0" from an interactive shell, not from a script. Maybe you put it into a script, but then sourced the script instead of calling it?

$ cat > 1.sh
#!/bin/bash
echo "$0"
$ chmod u+x 1.sh
$ ./1.sh
./1.sh

But

$ echo "$0"
bash
$ . ./1.sh
bash
choroba
  • 231,213
  • 25
  • 204
  • 289