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" ;;
    /) 
        if [ $num2 -eq 0 ]; then
            echo "Error: Division by zero is not allowed."
            exit 1
        fi
        result=$((num1 / num2))
        operation="division"
        ;;
    *) 
        result=$((num1 * num2))
        operation="multiplication"
        ;;
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 and division—by calculating the result accordingly. Additionally, it addresses division by zero by confirming whether the divisor is zero before proceeding with the division.

❹ 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

4.7/5 - (14 votes)
LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now
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.

2 thoughts on “How to Use Positional Parameters in Bash Script? [2 Examples]”

  1. Hello,

    I am currently in the process of learning bash script. If I am wrong let me know, but I think your first example with the arithmetic operations is incorrect. In your switch case statement, bash script automatically uses *) as the final case. This means that the division operation and the final catch all will not work, it will only do addition and subtraction. (i.e your first two examples).

    In order to get the bash script to run correctly, I needed to turn off blobbing with -o and instead of having *) I needed to change it to “*”) .This allowed multiplication to work. Again thankyou for your examples.

    Steve

    Reply
    • Thank you for bringing the loophole to my attention. Indeed, the problem is all about using the asterisk sign since it holds a built-in operation in case statements.

      To solve it, your proposition is a good way to go. However, I have run the code by turning off the globbing with set -o noglob command but did not get results for the division operation. Can you enlighten me a bit more about how you dealt with it?

      My two cents on this will be to either avoid using operator syntax in the command line entirely or put multiplication case in the last statement. For my second proposition, enclose the asterisk sign with a double quote whenever it is given to a positional argument. For instance, if we run the code for multiplication, the command will be ./arithmetic_parameters 45 5 "*". And the modified code is as given 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" ;;
      /)
      if [ $num2 -eq 0 ]; then
      echo "Error: Division by zero is not allowed."
      exit 1
      fi
      result=$((num1 / num2))
      operation="division"
      ;;
      *)
      result=$((num1 * num2))
      operation="multiplication"
      ;;
      esac
      echo "Performing $operation: $num1 $operator $num2 = $result"
      And the output for all arithmetic operations will now look like this:
      Using asterisk in case statement

      Reply

Leave a Comment