DEV Community

Cover image for Special Variables in Shell Scripting
Sathish Kumar
Sathish Kumar

Posted on

Special Variables in Shell Scripting

In this article, we will be seeing what are the special variables available and its purpose in shell scripting.

1. $0 - This variable will be provide the filename of the current script.

2. $n - These variables correspond to the arguments with which a script was invoked. Here n is a positive decimal number corresponding to the position of an argument (the first argument is $1, the second argument is $2, and so on).

3. $? - The exit status of the last command executed.

4. $$ - The process number of the current shell. For shell scripts, this is the process ID under which they are executing.

We will see the example scripts.

image

After running the above script,

image

5. $* - All the arguments are double quoted. If a script receives two arguments, $* is equivalent to $1 $2.

6. $@ - All the arguments are individually double quoted. If a script receives two arguments, $@ is equivalent to $1 $2.

Many will find the above variables will return the same output but there is subtle change.

Let me show you with the example, this time with rm(remove command) since echo will not show much difference.

image

Running the above script

image

$@ and $* returns the same output but "$@" took only double quoted argument as single argument and "$*" took entire arguments as single argument

7. $! - The process number of the last background command.

image

Hope it helps :)

Top comments (0)