Special Positional Parameters in BASH

In this article, we would cover special positional parameters in BASH. When we execute any script, any parameters which follows script command are the positional parameters. Understand it with the help of an example. Let’s say we have script myscript and we intend to pass following arguments with it – one, two, three and four –

myscript one two three four

Here, the first positional parameter is one, second positional parameter is two, third positional parameter is three and fourth is four. Here, $1 is the first positional parameter, $2 is the second positional parameter and so on. These are assigned values according to the order in which positional parameters are passed in the command-line. $0 is the name of the script itself.

To display all the arguments, we can use $@ – it starts from $1. To know the number of positional parameters on the command-line, we can use $#.

$? shows the exit status of most recently executed command. If its a success then, it will return with 0. $$ is used for the Process ID of the shell. At this point, it may start to look a bit confusing. But, with the following example – we hope things would get clear.

Special Positional Parameters in BASH

Let’s say we have script – myscript. Now, we append the file with following code –

#!/bin/bash
echo "The first argument - $1, the second argument - $2."
echo "The third argument - $3, the fourth argument - $4."
echo "The command for the script - $0."
echo "Number of parameters in our command-line - $#"
echo "Know if the most recently command-line successfully exited - $?"
echo "All the arguments passed are - $@"
echo "The PID of the shell - $$"

To make script executable –

chmod u+x myscript

And, issue the following to check for positional parameters –

./myscript one two three four

It would return with the following –

The first argument - one, the second argument - two.
The third argument - three, the fourth argument - four.
The command for the script - ./myscript.
Number of parameters in our command-line - 4
Know if the most recently command-line successfully exited - 0
All the arguments passed are - one two three four
The PID of the shell - 2454

The Process ID would be different for you. Apart from that, 0 in 5th echo command indicates the successful exit status of most recent executed command.

In conclusion, we saw how to check for special positional parameters in BASH with relevant example. Apart from that, if you want to know more about how to execute shell scripts in Ubuntu.

Similar Posts