Skip to main content
Bash

What is $0 in a Bash Script?

Get familiar with the special variable $0 in Bash and learn its usage.

Sagar Sharma

Warp Terminal

As you know, the $ sign in the bash is used to indicate the variables. This is a variable too but a different one.

The $0 is one of the special variables you get in bash and is used to print the filename of the script that is currently being executed.

The $0 variable can be used in two ways in Linux:

  • Use $0 to find the logged-in shell
  • Use $0 to print the name of the script that is being executed.

So let's start with the first one.

Find the logged-in shell using the $0

When not used in the script, the $0 holds the information of which shell you are currently using. So if you print the value of the $0, it will show you which shell you are currently logged in.

For example, here, I was logged in to bash in one window while in the other, I was using the zsh and printing the value of $0 using echo command reflected the names of the logged-in shells:

know the currently logged in shell in Linux

Now, let's jump to how it can be used in the scripts.

Use $0 in shell scripts

To use the $0 variable in the script, all you have to do is use a simple echo statement with this variable and it will print the filename.

For example, here I will be using a simple hello world script:

#!/bin/bash
echo "Hello World"

So if I have to use the $0 variable here, all I have to do is add the following line at the end:

echo $0

To make it more human-readable, you can also use something like this:

echo "The name of the script is: " $0

So the final result would look like this:

#!/bin/bash
echo "Hello World"
echo "The name of the script is: " $0

And this is the output it gave me when I executed the script:

use of the $0 variable in shell script

A small but effective variable. Isn't it?

More special variables in Bash

If you find this variable fascinating, there are more special variables in bash that can be used in different scenarios.

And if you want to learn more about them, we have a dedicated guide for that:

Special Variables in Bash Shell [With Script Examples]
The bash shell has some special variables that have specific usages and purposes. Learn more about them here.

I hope you will find this interesting. Have more ideas on what should I cover next? Feel free to leave a comment.

Sagar Sharma