Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't echo "$0" printing the script name in bash? [duplicate]

Tags:

linux

bash

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?

like image 364
Stefan Avatar asked Oct 19 '25 21:10

Stefan


2 Answers

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.

like image 76
Charles Duffy Avatar answered Oct 22 '25 10:10

Charles Duffy


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
like image 43
choroba Avatar answered Oct 22 '25 10:10

choroba