How to Use Positional Parameters in Bash Script? [2 Examples]

Positional parameters in Bash are values provided to a script or function when executed. They are accessed using bash parameters like $1, $2, $3, and so on, representing the first, second, third, and subsequent parameters respectively. In this article, I am going to discuss how you can use positional parameters in bash scripting.

Key Takeaways

  • Understanding the usability of positional parameters.
  • Getting familiar with the set and unset commands, and their functionality with positional parameters.

Free Downloads

What is a Positional Parameter?

Positional parameters refer to the input arguments supplied to your scripts during their execution. These arguments are accessible using variables ranging from $1 to $N, where N represents a numeric value.

In cases where N is comprised of more than a single digit, it should be enclosed within curly braces like ${N}. For example, consider the case where you want to access the value of the 10th positional parameter. You would use ${10} to avoid confusion with ${1}0, which could be mistakenly interpreted as the value of $1 followed by a ‘0‘. So, using ${10} ensures accurate parameter retrieval.

2 Practical Examples of Using Positional Parameters in Bash Scripting

As you have already got an idea of what are the positional parameters. Now let’s see how can you incorporate those parameters in a bash script. For this, I am going to provide 2 different examples of using positional parameters in a script.

Example 01: Performing Arithmetic Operation With Positional Parameters in Bash

In this first example, the script receives a pair of arguments and delivers the outcome of arithmetic operations ( Addition, Subtraction, multiplication, division) performed on these two integers.

Steps to Follow >

❶ At first, launch an Ubuntu Terminal.

❷ Write the following command to open a file in Nano:

nano arithmetic_parameters.sh
EXPLANATION
  • nano: Opens a file in the Nano text editor.
  • arithmetic_parameters.sh: Name of the file.

❸ Copy the script mentioned below:

#!/bin/bash

# Check if at least 3 positional parameters are provided
if [ $# -lt 3 ]; then
    echo "Usage: $0 <num1> <num2> <operator>"
    exit 1
fi

num1=$1
num2=$2
operator=$3
result=0

case $operator in
    +) result=$((num1 + num2)); operation="addition" ;;
    -) result=$((num1 - num2)); operation="subtraction" ;;
    *) result=$((num1 * num2)); operation="multiplication" ;;
    /) 
        if [ $num2 -eq 0 ]; then
            echo "Error: Division by zero is not allowed."
            exit 1
        fi
        result=$((num1 / num2))
        operation="division"
        ;;
    *)
        echo "Invalid operator: $operator"
        exit 1
        ;;
esac

echo "Performing $operation: $num1 $operator $num2 = $result"
EXPLANATION
The first line #!/bin/bash is called shebang line indicates that the Bash shell executes. The Bash script checks whether a minimum of three positional parameters has been provided. It then assigns these parameters to variables representing the first number, second number, and arithmetic operator.

Using a case statement based on the operator, the script executes the chosen arithmetic operation—addition, subtraction, or multiplication—by calculating the result accordingly. Additionally, it addresses division by zero by confirming whether the divisor is zero before proceeding with the division. Subsequently, the script showcases the outcome of the operation, coupled with a description of the specific operation undertaken. If the operator provided is unrecognized, the script promptly notifies that it constitutes an invalid operator and consequently exits.

❹ Press CTRL+O and ENTER to save the file; CTRL+X to exit.

❺ Use the following command to make the file executable:

chmod u+x arithmetic_parameters.sh
EXPLANATION
  • chmod: Changes the permissions of files and directories.
  • u+x: Here, u refers to the “user” or the owner of the file and +x specifies the permission being added, in this case, the “execute” permission. When u+x is added to the file permissions, it grants the user (owner) permission to execute (run) the file.
  • arithmetic_parameters.sh: File name.

❻ Run the script by the following command:

./arithmetic_parameters.sh 45 5 +
./arithmetic_parameters.sh 45 5 -

Performing Arithmetic Operation with Positional ParametersIf you run the provided script ./arithmetic_parameters.sh 45 5 + with the given command line arguments, the script returns Performing addition: 45 + 5 = 50, and Performing subtraction: 45 – 5 = 40 for ./arithmetic_parameters.sh 45 5 –.

Example 02: Set or Unset Positional Parameters in Bash Script

Using the built-in set command, you can set your positional arguments and double hyphen () for unsetting variables. Follow the code I am going to discuss below to learn more.

You can follow the steps of Example 01, to save & make the script executable.

Script (set-unset.sh) >

#!/bin/bash

# From command line
echo -e "Basename=$0"
echo -e  "\$1=$1"
echo -e "\$2=$2"
echo -e "\$3=$3"

# From Set builtin
set First Second Third
echo -e  "\$1=$1"
echo -e "\$2=$2"
echo -e "\$3=$3"

# Store positional parameters with -(hyphen)
set - -f -s -t
echo -e  "\$1=$1"
echo -e "\$2=$2"
echo -e "\$3=$3"

# Unset positional parameter
set --
echo -e  "\$1=$1"
echo -e "\$2=$2"
echo -e "\$3=$3"
EXPLANATION
The script begins by displaying positional parameters passed from the command line using the echo command. These parameters are accessed using the $1, $2, and $3 variables, representing the first, second, and third arguments, respectively. The script then uses the set command to set new values for the positional parameters. This replaces the original command-line parameters. The updated values are displayed using echo statements.

Next, the script employs the set command with hyphens to set positional parameters (-f, -s, -t). These hyphens are treated as arguments themselves, and the resulting values are shown using echo statements. Finally, the script uses the set command with double hyphens () to unset all positional parameters. As a result, subsequent echo statements display empty values for the positional parameters.

Copy and paste the following command to run the script:

./set-unset.sh 25 5 2

Using set or unset Positional Parameters in Bash ScriptUpon executing the provided script ./set-unset.sh with the command line arguments 25 5 2, the output will look like the above image

Assignment Task

Down below, I am going to give you two assignment tasks to learn and try by yourself. Don’t forget to share your experience in the comment section.

  • Write a Bash script that takes three commandline arguments: a username, age, and city. The script should display a personalized message using the provided information. If the city has more than one word, enclose it in quotes.
  • Create a Bash script named sh that takes some filenames as command-line arguments. The script should check each file’s existence and display whether it exists or not.

Conclusion

In conclusion, this article has discussed how to use positional parameters in a bash script. Though you can make code as much as you want using the bash parameter, here I have demonstrated two different examples, Hope it will work as a guide to learning the bash language, and don’t forget to explore more. If you have any questions or queries regarding this article, feel free to comment below. Thank You!

People Also Ask

What are the positional parameters?
Positional parameters are values supplied to a script or function when it’s called, accessible using special variables like $1, $2, …, $n.

What is the difference between $@ and $* in bash?
In Bash, $@ treats arguments as separate entities, preserving spaces. $* treats all as a single entity, affected by IFS.

What is $# in bash script?
$# is a special parameter in shell scripting. In a bash script, $# represents the number of arguments (parameters) passed to the script or function.

What does $_ mean in shell?
$_ is a special parameter in shell scripting. In a shell, $_ refers to the last command’s last argument. It’s a special variable for convenience.

Related Articles


<< Go Back to Parameters in Bash Scripting | Bash Scripting Tutorial

5/5 - (13 votes)
Mohammad Shah Miran

Hey, I'm Mohammad Shah Miran, previously worked as a VBA and Excel Content Developer at SOFTEKO, and for now working as a Linux Content Developer Executive in LinuxSimply Project. I completed my graduation from Bangladesh University of Engineering and Technology (BUET). As a part of my job, i communicate with Linux operating system, without letting the GUI to intervene and try to pass it to our audience.

Leave a Comment