How does "echo $0" work?

10,834

$0 is a special parameter in Bash…

…and other POSIX standards compliant shells as well.

As explained in this comment on that answer you link to, echo $0 simply shows you the name of the currently running process:

$0 is the name of the running process. If you use it inside of a shell then it will return the name of the shell. If you use it inside of a script, it will be the name of the script.

More details can be found here on this other site:

$0 is one of the Bash special parameters. It can only be referenced as follows (just an example as there are various ways to reference and use $0 while scripting).

So just create a Bash script like this. First open up a file for writing called test.sh with Nano like this:

nano test.sh

Then put these contents into that file:

#!/bin/bash
echo $0

Then hit Ctrl+X, save the file. Now make the script executable like this:

chmod 700 test.sh 

Now run it like this:

./test.sh

And the output would be:

./test.sh

So for the purposes you describe echo $0 won’t really work.

Share:
10,834
Sun - FE
Author by

Sun - FE

Updated on September 18, 2022

Comments

  • Sun - FE
    Sun - FE almost 2 years

    I found out on Ask Ubuntu I can use this command to figure out what shell I am in.

    echo $0
    

    I like this because it is simple as compared to more complex solutions like this one on the Unix and Linux Stack Exchange.

    I imagine echo is similar to print but what is the $0?

    Eventually I would like to be able to open up multiple tabs programmatically similar to seen here on Stack Overlow.

    That uses gnome-terminal but I am using Bash.