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?
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 source
d, 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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With